Special FX, Colour reduction

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'll see when you run the code. 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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Special FX, Interlacing >>

Previous chapter: Introduction to special effects using simple algorithms

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.