Fast and realistic color replace using PNG transparency

The change color in photo demo you see on the Chameleon page (click on the "photo demo" button in the upper left) is done simply by changing the background color behind a specially prepared PNG image which has an alpha channel. Each pixel in that image has 4 values: red, green, blue, and "alpha," or degree of transparency. Changing the color behind the image creates the appearance that one object in the photo is changing color...and, in theory anyway, all the shading and reflections on the object appear correct. This doesn't just apply to hue changes (for instance, changing the background color to blue or red), but should work even if the background color is changed to white, black, gray, and various tints and shades of hues.

Because alpha compositing is generally handled at the hardware level (your graphics chip can do this number crunching without taxing your CPU), it goes quite fast. Although the color change itself is driven by javascript -- not exactly the fastest language in the world -- there is no need for the javascript to process each pixel in the photo as you move the slider about on the color picker. Instead, it only needs to change a single color: that of the background.

To make this work, though, the image has to be prepared properly ahead of time -- essentially stripping out a single color and replacing it with an appropriate degree of transparency for each pixel. Doing it correctly, though, is less than trivial, and -- while I could be wrong -- I think my technique is unique. I certainly haven't seen it done like this on the web, using translucent PNGs and attempting to keep a photographic image realistic over the full gamut of possible hues, tints and shades. If someone is doing this elsewhere (say, as part of a sophisticated image manipulation program), it surprises me that it wouldn't occur to anyone to do the final trivial step of producing such PNG images and putting them on the web, due to the fairly obvious utility of doing so.

So in these two articles -- 1 and 2 -- I describe in some technical detail how I go about the preparation of the PNG image: converting a regular 3 channel image to a 4 channel one, such that this technique works and it appears correct. If, after getting some feedback, it appears that I really have something new here, I plan on building it into a polished, easy to use piece of software that others can use to build these 4 channel images.