ImageIO.read( ) always rotates my uploaded picture

拟墨画扇 提交于 2019-12-03 06:47:48

ImageIO.read( ) can't read the orientation of the image if it was taken with mobile device.

I used metadata-extractor to read metadata, i think it's a good solution: github.com/drewnoakes/metadata-extractor/wiki

<dependency> 
  <groupId>com.drewnoakes</groupId> 
  <artifactId>metadata-extractor</artifactId> 
  <version>2.7.2</version> 
</dependency>

Read orientation filed in exif directory:

ExifIFD0Directory exifIFD0 = metadata.getDirectory(ExifIFD0Directory.class);
int orientation = exifIFD0.getInt(ExifIFD0Directory.TAG_ORIENTATION);

switch (orientation) {
  case 1: // [Exif IFD0] Orientation - Top, left side (Horizontal / normal)
    return null;
  case 6: // [Exif IFD0] Orientation - Right side, top (Rotate 90 CW)
    return Rotation.CW_90;
  case 3: // [Exif IFD0] Orientation - Bottom, right side (Rotate 180)
    return Rotation.CW_180;
  case 8: // [Exif IFD0] Orientation - Left side, bottom (Rotate 270 CW)
    return Rotation.CW_270;
}

(Rotation is a class from the org.imgscalr.Scalr framework I use ti rotate image).

Quite interesting issue... you can try to fix it by introducing a check on the image width and height to be larger than 2448 and 3264 respectively and then just swap its width and height

Use below piece of code:

BufferedImage oldImage = ImageIO.read(file.getInputStream());

if (oldImage.getWidth() > 2448 || oldImage.getHeight() > 3264) {

    BufferedImage newImage = new BufferedImage(oldImage.getWidth(),
                oldImage.getHeight(), oldImage.getType());

    Graphics2D graphics = (Graphics2D) newImage.getGraphics();

    graphics.drawImage(oldImage, 0, 0, oldImage.getHeight(),
                oldImage.getWidth(), null);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

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