Thumbnailator Image Rotation messes the image

1.6k views Asked by At

I am trying to rotate images using Thumbnailator library. The code that I use is as shown below. It rotates the image or flips the image successfully but the color quality completely spoils. The input and output images are also shown.

package com.abk;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.Flip;
import net.coobird.thumbnailator.filters.Rotation;
import net.coobird.thumbnailator.util.exif.ExifUtils;
import net.coobird.thumbnailator.util.exif.Orientation;

public class ImageAutoRotate {
    public static void main(String[] args) {
        try {
            BufferedImage img = ImageIO.read(new File("314.jpg"));
            BufferedImage newImg = Rotation.RIGHT_90_DEGREES.apply(img);
            BufferedImage flipImg = Flip.HORIZONTAL.apply(img);

            File outputfile = new File("314_2.jpg");
            ImageIO.write(newImg, "jpg", outputfile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Input Image enter image description here Output Image Output Image

2

There are 2 answers

0
The Cloud Guy On BEST ANSWER

Resolved the issue by saving the image as a PNG image. The issue was actually caused because the image profile was being treated as CMYK while saving

The final code to resolve this issue is shown at this link

0
Muhammad Taimour On

Had the same issue it is due to the ImageIO.write class. Following is the approach I used.

//Here imagebuffer is an array of bytes you can convert it from bufferedimage

InputStream fiStream = new ByteArrayInputStream(imageBuffer);

//Creating a file using byte array

FileUtils.writeByteArrayToFile(new File(path + "/webapps/northstar- 
primefaces-portlet/images/member/" + event.getFile().getFileName()), imageBuffer);

//Creating an output stream using the created file

OutputStream out = new FileOutputStream(path + "/webapps/northstar-primefaces-portlet/images/member/"  + event.getFile().getFileName());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Thumbnails.of(fiStream).scale(1).toOutputStream(outputStream);

//Now the outstream has the rotated image with the correct colours

Let me know if this helps.

Reference: https://github.com/coobird/thumbnailator/issues/23