in reply to GD - Two colors?
The script works by manipulating indexes, replacing the palette entries with one of two rgb values depending upon the threshhold calculation. GD doesn't make any attempt to compress the pallete. You've told it that the image contains 256 'colors'--despite that they all map to one of two sets of rgb values--so it doesn't attempt to discard any 'reduntant' palette entries.
You can achieve what you want by creating a new image that has only two palette entries and mapping the pixels across yourself. This runs more slowly, but results in a 1-bit BW image output rather than a 8-bit color with all the entries mapped to black or white. Ie. Much smaller images.
The following code does that, and produces an output file with the same name as the input prefixed with 'BW-'. I've also made the threashhold a command line parameter -T=nn: values range from 0 .. 255 per the original algorithm.
#! perl -slw use strict; use GD; our $T ||= 150; my $file = shift @ARGV; die "$file not found" unless -e $file; my $in = GD::Image->new( $file ) or die $!; my( $w, $h ) = $in->getBounds; ## New palette image with just two colors my $out = GD::Image->newPalette( $w, $h ); my $black = $out->colorAllocate( 0, 0, 0 ); my $white = $out->colorAllocate( 255, 255, 255 ); for my $y ( 0 .. $h - 1 ) { for my $x ( 0 .. $w -1 ) { my( $r, $g, $b ) = $in->rgb( $in->getPixel( $x, $y ) ); ## Map the pixels relative to the threshhold my $index = (( $r = $g +$b ) / 3) > $T ? $black : $white; $out->setPixel( $x, $y, $index ); } } open OUT, '>:raw:perlio', "BW-$file" or die $!; print OUT $out->png( 9 ); close OUT; #system 1, "BW-$file"; ## display image
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: GD - Two colors?
by Anonymous Monk on Aug 07, 2007 at 19:40 UTC |