Surplus Palette Entry When Saving PNG File with Indexed Colors
ImageMagick version
7.1.2-11
Operating system
Windows
Operating system, version and so on
7 Version 6.1.7601
Description
When determining the palette for an image by counting the unique colors, IM is off by one in most cases. The reason why this matters (other than the palette size just being too large by 3 bytes) is that this number also influences the bit depth used to express a palette index. This may result in considerably bigger file sizes in cases where the number of colors is on the edge to a next higher bit depth, namely 2, 4, and 16 colors, which are fairly common cases.
Note that for some strange reason, this off-by-one error does not occur when the image previously contained a completely transparent color which was -alpha removed.
Also note that this error used to occur for 256 colors as well in some previous versions of IM, for instance 7.1.0-2, which effectively prevented the usage of a palette. It seems that at some point, a derogation for exactly this number of colors was added to IM instead of solving the counting issue altogether.
Steps to Reproduce
magick xc:red xc:green +append 2wrong.png
magick 255.png 255wrong.png
magick xc:red xc:none +append -alpha remove +append 2right.png
magick 256.png 256right.png
magick identify -verbose 2wrong.png 255wrong.png 2right.png 256right.png | findstr "entries:"
magick identify -verbose 2wrong.png 255wrong.png 2right.png 256right.png | findstr "bit_depth:"Actual result:
Colormap entries: 3
Colormap entries: 256
Colormap entries: 2
Colormap entries: 256
png:IHDR.bit_depth: 2
png:IHDR.bit_depth: 8
png:IHDR.bit_depth: 1
png:IHDR.bit_depth: 8Expected result:
Colormap entries: 2
Colormap entries: 255
Colormap entries: 2
Colormap entries: 256
png:IHDR.bit_depth: 1
png:IHDR.bit_depth: 8
png:IHDR.bit_depth: 1
png:IHDR.bit_depth: 8Images
255.png
256.png
Source: ImageMagick/ImageMagick