Pink/Reddish tint while resizing jpeg images using java thumbnailator or imgscalr

爱⌒轻易说出口 提交于 2019-12-18 06:12:37

问题


I am trying to convert an image (url below) using two libraries (thumbnailator and imgscalr. My code works on most of the images except a few which after conversion have a pink/reddish tint.

I am trying to understand the cause and would welcome any recommendation.

Note - Image type of this image is 5 i.e BufferedImage.TYPE_3BYTE_BGR and i am using Java 7

Using Thumbnailator

  Thumbnails.of(fromDir.listFiles())                
                    .size(thumbnailWidth, thumbnailHeight)
                    .toFiles(Rename.SUFFIX_HYPHEN_THUMBNAIL);

Using imgscalr

    BufferedImage bufferedImage = ImageIO.read(file);
    final BufferedImage jpgImage;

    LOG.debug("image type is =[{}] ", bufferedImage.getType());

     BufferedImage scaledImg = Scalr.resize(bufferedImage, Method.ULTRA_QUALITY, thumbnailWidth, thumbnailHeight, Scalr.OP_ANTIALIAS);


    File thumbnailFile = new File(fromDirPath + "/" + getFileName(file.getName()) +THUMBNAIL_KEYWORD  + ".png");

    ImageIO.write(scaledImg, getFileExtension(file.getName()), thumbnailFile);

    bufferedImage.flush();
    scaledImg.flush();

回答1:


I get this question a lot (author of imgscalr) -- the problem is almost always that you are reading/writing out different file formats and the ALPHA channel is causing one of your color channels (R/G/B) to be culled from the resulting file.

For example, if you read in a file that was ARGB (4 channel) and wrote it out as a JPG (3 channel) - unless you purposefully manipulate the image types yourself and render the old image to the new one directly, you will get a file with a "ARG" channels... or more specifically, just Red and Green - no Blue.

PNG supports an alpha channel and JPG does not, so be aware of that.

The way to fix this is to purposefully create appropriate BufferedImage's of the right type (RGB, ARGB, etc.) and using the destImage.getGraphics() call to render one image to the other before writing it out to disk and re-encoding it.

Sun and Oracle have NEVER made the ImageIO libraries smart enough to detect the unsupported channels when writing to differing file types, so this behavior happens all the time :(

Hope that helps!




回答2:


The following piece of code resolved my issue:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

  Thumbnails.of(new ByteArrayInputStream(imageByteArray))
    .outputFormat("jpg")
    .size(200, 200)
    .toOutputStream(outputStream);

  return baos.toByteArray();

I am using Thumbnailator and the code was posted here: https://github.com/coobird/thumbnailator/issues/23



来源:https://stackoverflow.com/questions/26115851/pink-reddish-tint-while-resizing-jpeg-images-using-java-thumbnailator-or-imgscal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!