coobird / thumbnailator

Thumbnailator - a thumbnail generation library for Java
MIT License
5.14k stars 784 forks source link

Broken colors when processing PNG #165

Closed pavel-klavik closed 3 years ago

pavel-klavik commented 3 years ago

Expected behavior

The colors in hungary_broken.png are broken. They should be the same as in hungary.png.

Actual behavior

The images:

hungary.png hungary_broken.png

Steps to reproduce the behavior

I am running the following code:

Thumbnails/of("hungary.png")
  .scale(1)
  .outputFormat("png")
  .toFile("hungary_broken.png");

Environment

I have the following TwelveMonkeys packages included, probably unrelated to the problem:

[com.twelvemonkeys.imageio/imageio-jpeg "3.5"]
[com.twelvemonkeys.imageio/imageio-tiff "3.5"]
[com.twelvemonkeys.imageio/imageio-batik "3.5"]
coobird commented 3 years ago

For this particular case, it appears that the input image (PNG) is using an indexed color palette. It's been observed in the past that in this mode, the processed image can end up with a dithering effect.

One can avoid this dithering effect by forcing Thumbnailator to use a image mode with more colors. For example, the following will force Thumbanailator to use the 32-bit color mode (RGB with alpha), leading to a cleaner image.

Thumbnails/of("hungary.png")
  .scale(1)
  .imageType(BufferedImage.TYPE_INT_ARGB)
  .outputFormat("png")
  .toFile("hungary_broken.png");

(Note that more colors are being used, the final image may be larger than using an indexed color palette.)

pavel-klavik commented 3 years ago

Does this setting work for all PNG images? I am using this to automatically convert images uploaded by users. I don't really care whether the generated file will be slightly larger.

coobird commented 3 years ago

@pavel-klavik, I can't guarantee anything, but it'll likely work better than not specifying .imageType.

coobird commented 3 years ago

Closing as duplicate of #26.