Question

I am trying to programmatically reduce (lossy) the file size of PNG and GIF files. As part of this I need to reduce the number of colors in the images. I don't want to reduce all the images to a single colors value, so what I am doing is; get the number of unique colors in the image, then; divide this number by 2 to reduce the number of colors by half.

The problem is this does not work. Using ImageMagic it is way too slow and doesn't reduce the file size unless the image has under a few hundred unique colors. Using GraphicsMagick always results in a unique colors value under 255 regardless of how many colors were in the original image. Another problem with GraphicsMagick is if there are any transparent pixels in the image it replaces the lost colors with transparent.

Any help would be gratefully welcome, Thanks.

Was it helpful?

Solution 3

First problem, GraphicsMagick can be compiled using 8 bit, 16 bit or 32 bit quantum levels. My version is compiled into 8 bit (the default), this means that the max number of colors that can be assigned to an image is 256 unique colors (3*3*2, 1 of the blue bits is removed because the human eye can't see it properly). Obviously, GraphicsMagick can handle images with more colors than this but when reducing colors it can only reduce to 256 or less colors. Larger pixel quantums cause GraphicsMagick to run more slowly and to require more memory. For example, using sixteen-bit pixel quantums causes GraphicsMagick to run 15% to 50% slower (and take twice as much memory) than when it is built to support eight-bit pixel quantums.

Second problem; transparency handling in PNG images, I was using an earlier version of GraphicsMagick (1.1 I think), anyway, when I upgraded to 1.3 this problem is no longer present which tells me that it was a bug in GraphicsMagick 1.1 that caused this.

OTHER TIPS

Reducing the number of colors is only useful if

  1. the image can then use a palette instead of storing the color for each pixel
  2. the size of a palette index is smaller than the size of a color
  3. the image format supports the palette size

I think you can only get 1-bit, 4-bit, 8-bit, so 2-color, 16-color, or 256-color in those formats. I think if you ask for more, you just get truncated to 256. If you ask for less, it just doesn't use the entire palette.

Have you considered converting to JPEG and playing with the quality setting? You end up with more fine grain control of lossy-ness. The drawback is if the images aren't photos, but it sounds like they have a lot of colors, so they might be.

Perhaps choose 1, 4, 8 bit if it's close to what you want and jpeg if it has a lot of colors.

I think the ImageMagick facility you are after might be quantization:

http://www.imagemagick.org/Usage/quantize/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top