Hello,
I'm using the following snippet I found on perlmonks and have tried altering the code to transform a title image I have from color to black and white with the text being all black and the background being all white. I've had success doing this but when I save the file it still saves it using 256 colors.

Is there anyway to allocate just black and white before saving it to decrease the file size?

The code snippet is below:

use warnings; use strict; use GD; my $file = $ARGV[0]; chomp $file; convert_to_bw($file); sub convert_to_bw { my $in_file = shift; my $image = GD::Image->new("$in_file"); unlink $in_file; my $ni_file = $in_file; my $i = 0; my $t = $image->colorsTotal(); while($i < $t) { my( @c ) = $image->rgb( $i ); # Convert the color image to black and white my $g = ( $c[0] + $c[1] + $c[2] ) / 3; $image->colorDeallocate($i); $image->colorAllocate( $g, $g, $g ); my( @d ) = $image->rgb( $i ); # Replace the background color with white if ($d[0] > 150) { $image->colorDeallocate($i); $image->colorAllocate( 255, 255, 255 ); } my( @e ) = $image->rgb( $i ); # Replace the text with black if ($e[0] > 10 && $e[0] < 255) { $image->colorDeallocate($i); $image->colorAllocate( 0, 0, 0 ); } $i++; } my $colorsTotal = $image->colorsTotal(); print "COLOR TOTAL: $colorsTotal\n"; write_file( $ni_file, $image->png(9) ); } sub write_file { my $i = shift; open DISPLAY, ">$i" or warn "can't clobber $i $!"; binmode DISPLAY; print DISPLAY @_; close DISPLAY; }

In reply to GD - Two colors? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.