Name

colors — preferred number of colors

Synopsis

$image->Set(colors=>integer)
$image->Get('colors')

The colors attribute allows you to specify the maximum number of colors that an image will have after the Quantize( ) method is called. If an image has fewer unique colors, any duplicate or unused colors will be removed from the colormap. The colorspace and dither attributes also affect the results of reducing the number of colors in an image. The default colorspace for color reduction is RGB; you may get better results by first changing the colorspace to YUV or YIQ. The following example illustrates a way to preserve the transparency of an image when reducing the number of colors by first transforming the image to the Transparent colorspace:

#!/usr/bin/perl

use Image::Magick;

my $image = Image::Magick->new;
$image->Read('dog.gif');
$image->Transparent('#FFFFFF');

# Reduce to three colors, one of which is the transparent
#
$image->Quantize(colorspace=>'Transparent', colors=>3);
$x = $image->Display();
undef $image;

If you want to make the image black and white, set the number of colors to 2 and the colorspace to Gray. You can also set the dither attribute if you want black and white dithered approximations of colors.

See also the descriptions for colorspace and dither.

Get Programming Web Graphics with Perl and GNU Softwar now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.