Search code examples
javaalgorithmimagemagickgifquantization

Color quantizing giving very bad results?


I'm trying to get my application to export animated gifs, however, once the colors exceed 256, the quantization algorithm kicks in and things get, wrong.

Here's the file I have being converted, and what the algorithm converts it to:

enter image description here

The quantization algorithm I'm using is this, Quantize.java, it's apparently a Java port of the quantization used in ImageMagick so I feel like it should be reliable?

I'm using it like so:

protected int[][] pixels;  // 2D array of RGB pixels of image
protected byte[] indexedPixels;

// ...

/**
 * Analyzes image colors and creates color map.
 */
protected void analyzePixels()
{
    // Quantize the pixels, get reduced color map and indexed array.
    // -------------------------------------------------------------
    colorPalette = Quantize.quantizeImage(pixels, 256);

    // Create indexed pixels array.
    // ----------------------------
    int i = 0;

    for (int x = 0, xSize = pixels.length; x < xSize; ++x)
    {
        for (int y = 0, ySize = pixels[x].length; y < ySize; ++y)
            indexedPixels[i++] = (byte) pixels[x][y];
    }
}

Note - Here's what the algorithm converts it to when I set the static final boolean QUICK to false:

enter image description here

It looks different, but still not right.

I'd really love to get this algorithm working, since it's fast(er) and produces smaller files than the alternatives (NeuQuant). Am I doing everything right or is this just how the algorithm works?


Solution

  • I ended up abandoning Quantize.java and found Java Imaging Utilities (http://sourceforge.net/projects/jiu/) which provides some nice color/image quantizing options. They're not perfect results, but are bearable.