use GD;
sub getindex {
my $image = shift;
my $index = $image->colorExact(@_);
$index == -1 ?
$image->colorAllocate(@_) :
$index;
}
####
my $reference_image = new GD::Image(100,100);
my @colornames;
{
my $goodline = qr/^\d/;
open my $rgbdat, '<', '/usr/X11/lib/X11/rgb.txt'
or die $!;
while (<$rgbdat>) {
/$goodline/ or next;
my @dat = split " ", $_, 4;
my $color = pop @dat;
$colornames[getindex($reference_image, @dat)] = $color;
}
close $rgbdat or die $!;
}
##
##
my $image = GD::Image->newFromJpeg('many.jpg') or die $!;
my @size = $image->Bounds();
##
##
my $new_image = GD::Image->new @size;
##
##
{
my ($ix, $iy, @rgb); # preallocate and reuse
for $ix (0 .. $size[0]-1) {
for $iy (0 .. $size[1]-1) {
@rgb = $image->rgb(image->getPixel($ix,$iy)));
@rgb = $reference_image->rgb( $reference_image->colorClosestHWB( @rgb ));
$new_image->setPixel($ix, $iy, getindex($new_image, @rgb));
}
}
}
##
##
sub getcolor {
return "puke" unless @_ == 3;
$colornames[$reference_image->colorClosestHWB(@_)]
}