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 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.

 

Next chapter: Special FX, Interlacing >>

Previous chapter: Introduction to special effects using simple algorithms

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar