Pink / reddish tint when resizing jpeg images using java sketch or imgscalr

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

I am trying to understand the reason and welcome any recommendation.

Note Image Type of this image: 5 ie BufferedImage.TYPE_3BYTE_BGR and I use Java 7

enter image description hereenter image description here

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(); 
+6
source share
2 answers

I ask this question a lot (by imgscalr) - the problem is almost always that you read / write different file formats, and the ALPHA channel causes one of your color channels (R / G / B) to be selected from the resulting file.

For example, if you read in an ARGB file (4 channels) and write it as JPG (3 channels) - if you do not purposefully manipulate the image types themselves and render the old image directly, you will get a file with "ARG" channels ... or, more specifically, only red and green are blue.

PNG supports the alpha channel, and JPG does not, so keep that in mind.

To fix this, you need to purposefully create the appropriate BufferedImage of the desired type (RGB, ARGB, etc.) and use the call destImage.getGraphics() to render one image to another before writing it to disk and transcoding it.

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

Hope this helps!

+6
source

The following piece of code solved my problem:

 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

+1
source

Source: https://habr.com/ru/post/1203689/


All Articles