Hudzilla.org - the homepage of Paul Hudson
Contents > Multimedia > Images Wish List | Report Bug | About Me ]

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.





<< 11.2.16 Introduction to special effects using simple algorithms   11.2.18 Special FX, Interlacing >>
Table of Contents
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!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Be the first to add a comment to this chapter!



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is zero plus ten?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow