lvandeve / lodepng

PNG encoder and decoder in C and C++.
zlib License
2.07k stars 422 forks source link

Alpha information lost in some cases #12

Closed tomgrus closed 9 years ago

tomgrus commented 9 years ago

When encoding images with alpha information that could otherwise use a palette, alpha information is discarded.

My specific use case: I open an image with lodepng_decode32_file, then based on its luminance value I output a white color with only the alpha set to said luminance value. Using lodepng_encode32_file then outputs a plain white palletized image (P8).

I was able to fix this changing

palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8;

to

palette_ok = !prof.alpha && n <= 256 && (n * 2 < w * h) && prof.bits <= 8;

in the lodepng_auto_choose_color function. The output is then in A8L8.

I'm not entirely sure if this is considered a bug or a feature :). But since I'm expecting the encode to be a lossless process, I'm reporting this.

Also thanks so much for this library, it's a great and compact alternative to libpng!

lvandeve commented 9 years ago

Hello,

What was the exact image? I could use it as a test case to ensure there is no bug.

The intended behaviour is that if there are less than 257 colors, LodePNG writes the alpha channels in the tRNS chunk (see point 4.2.1.1. here: http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html).

So there are multiple ways that a PNG image file can be semi-translucent: either it uses the RGBA or Grey+Alpha color format, or, it uses a palette, with a tRNS chunk containing the alpha value for each palette index. Of course the latter method has smaller filesize, so is chosen for less than 257 colors.

Normally, most software reads that tRNS chunk, but in theory is allowed to ignore it. What program do you view the PNG image with?

Thanks!

tomgrus commented 9 years ago

Hey, you're right! It was Paint Shop Pro 7 (very very old, but it does what I need and I'm used to it). Other software deals with the output just fine.

Thanks and sorry!

lvandeve commented 9 years ago

No problem, interesting to know. I'll consider adding a setting (no promises tho :)) for this, after all the PNG spec specifically mentions software is allowed to ignore it...

abetusk commented 8 years ago

Just FYI, I ran into this same problem while using the C function lodepng_encode32_file. Viewing the PNG in Gimp and it looks like there's only two states for the alpha channel. In Gimp for the output PNG, some pixels look to be completely translucent when they go below a certain threshold while others aren't, but it's either all or none.

Using Imagemagick to convert to a BMP and then viewing through Gimp renders just fine so the alpha channel is definitely there and isn't being lost.

I don't know what the answer is but you might want to consider defaulting to 8-bit RGBA instead of trying to be clever and using a colormap.