A long time ago I wrote a GIFEncoder class which saved a Java image as a GIF. Unfortunately, this class only worked if the image contained less than 256 colors. No mechanism was provided to reduce an image to less than 256 colors, making GIFEncoder useless for many applications.
Recently, I finally had a reason to write a color reducer (otherwise known as a color quantizer). Quantize is a class which takes an image and reduces it to a specified number of colors. To use it, call quantizeImage() with a 2D RGB pixel array and the desired number of colors in the final image. This implementation is based entirely on ImageMagick's C++ source, by John Cristy, and is quiet efficient. For a lengthy explanation of how the algorithm works, check out Octree Color Quantization by Nils Pipenbrinck.
Version 0.90 was released on September 19, 2000.
Here is a sample of Quantize in action (jdk 118, w/ JIT, under Win2K). The original orange.jpg contained 14783 colors.
> java TestQuantize orange.jpg 1000 500 200 100 50 10 3 reduced to 1000 in 60ms reduced to 500 in 40ms reduced to 200 in 30ms reduced to 100 in 20ms reduced to 50 in 20ms reduced to 10 in 10ms reduced to 3 in 10ms |
produces:
A larger image (1000 x 1000, 300000 colors) takes 800ms to reduce to 1000 colors.