Color replacement in PHP, pixel by pixel

If you’re crazy enough to process an image pixel by pixel in PHP, then you can replace a color with another.

You can get decent results for vector graphics, but it’s slow.

On this one, I won’t explain the code, I’ll just post it and let you figure it out, it has some comments.

The code could be better, but I don’t really have the time or the will to  improve it.

A quick example

Let’s say you have this image (the Ubuntu wallpaper):

Original image

And for some reason, you want to replace the oranges with some sort of violet. You can use Photoshop, or Gimp, or a PHP script to get this:

Image with colors replaced by the PHP script

Above is the result of the script, after 3 seconds of processing.

Download the PHP code

Here is the script: color.tar.bz2. If you can find a use for it, by all means use it.

I have to give credit to Paul Bourke for the HSVToRGB and RGBToHSV functions that I ported to PHP.