Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: GD - Two colors?
by BrowserUk (Patriarch) on Aug 06, 2007 at 21:12 UTC | |
by Anonymous Monk on Aug 07, 2007 at 19:40 UTC |