Java识别图片的宽高相反的问题

这是由于手机拍摄图片的时候,会将方向等信息写入图片的exif信息部分。在电脑打开时,电脑已经自动识别其中的信息并且旋转图片,但是通过java的BufferedImage读取时,并不会自动读取exif的信息,因此会出现这种问题。

要解决这个问题,需要我们手动读取exif信息,识别出如果图片需要旋转,则根据旋转角度判断长宽是否需要对换。

首先我们引入一个jar包,用于读取exif信息

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

然后可以使用如下代码获得正确的宽高

/**
 * 根据原图片的Exif信息中方向,获得真实宽高
 */
public void getTrueWidthAndHeight(File imageFile) throws ImageProcessingException, IOException {
    BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
    Metadata metadata = ImageMetadataReader.readMetadata(imageFile);

    Directory imageDirectory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);

    int orientation = 1;
    try{
        orientation = imageDirectory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
    } catch (MetadataException ignore) {

    }

    boolean rotation = false;
    switch (orientation) {
        case 5: // - PI/2 and Flip X
        case 6: // -PI/2 and -width
        case 7: // PI/2 and Flip
        case 8: // PI / 2
            rotation = true;
    }

    if (rotation) {
        System.out.println("图片宽度: " + bufferedImage.getHeight());
        System.out.println("图片高度: " + bufferedImage.getWidth());
    } else {
        System.out.println("图片宽度: " + bufferedImage.getWidth());
        System.out.println("图片高度: " + bufferedImage.getHeight());
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值