11.2.17 Special FX, Colour reduction: imagetruecolortopalette()This is NOT the latest copy of this book; click here for the latest version.
void imagetruecolortopalette ( resource &image, bool dither, int num_colours)
The first effect is colour reduction, which is where a true colour image is converted to a paletted image. This is handled using the ImageTrueColorToPalette() function, which is a name so long you will be glad we have been capitalising each word in the image function names!
The function takes three parameters, which are an image to alter, whether to use dithering, and how many colours you would like in the final palette. It returns nothing, because the image is passed in as a reference for speed. The second parameter is critical to how the finished result looks: if you enable dithering by passing in true here, PHP will speckle the image to make it appear to have more colours than it actually has. Surprisingly, enabling dithering is not always a good thing - it makes the filesize larger, for example.
The code for this is quite simple:
<?php
set_time_limit(0);
$image = imagecreatefrompng("space.png");
imagetruecolortopalette($image, true, 64);
header("image/png");
imagepng($image);
imagedestroy($image); ?>
The result is quite noticeable, as you can see below. Switching an image from colour to a palette is a great way to cut down its size - even if the palette is 256 colours.

Note that the call to set_time_limit() is not really important for this particular effect, but is pretty much required for some of the others.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|