javajavax.imageioimgscalr

Image Resolution Changing but I am only trying to rotate the image


Any reason this code would changing the resolution of the original JPEG? I can understand if the file size were different because the JPEG quality settings are probably different but I don't understand why this would be resizing an image.

File newfile=new File(mydestinationfolder.concat(imagename));
Files.move(file.toPath(),newfile.toPath(), REPLACE_EXISTING);
Rotation Orientation;
if ((Orientation=Exif_data.get_Exif_Orientation(newfile)) != null) {

    System.out.println(Orientation.toString());
    BufferedImage oldimage = ImageIO.read(newfile);
    BufferedImage tmp = Scalr.rotate(oldimage, Orientation);
    oldimage.flush();
    oldimage=tmp;
    ImageIO.write(oldimage, "JPEG", newfile);

}

Solution

  • Well I am not sure why but the default settings for ImageIO.write() are changing the resolution. If I define a custom writer with JPEG quality set to 100%, the image resolution stays the same.

    NOTE: output.close() at the end is important because as long as the stream is open the file is locked.

    BufferedImage oldimage = ImageIO.read(newfile);
    BufferedImage tmp = Scalr.rotate(oldimage, Orientation);
    oldimage.flush();
    oldimage=tmp;
    Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter)iter.next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    float quality=1.0f;
    iwp.setCompressionQuality(quality);
    
    FileImageOutputStream output = new FileImageOutputStream(newfile);
    writer.setOutput(output);
    
    IIOImage image = new IIOImage(oldimage, null, null);
    writer.write(null, image, iwp);
    writer.dispose();
    output.close();