java - 检查是否有旋转角度导致ImageIO获取宽高相反

导入依赖

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

 

获取图片宽高

 public static ImgWH getImgWH(File file, String url) {
        if (null == file) {
            if (StringUtils.isEmpty(url)) return null;
            file = new File(url);
        }
        if (!file.exists()) return null;
        ImgWH wh = new ImgWH();
        try {
            Image img = ImageIO.read(file);
            wh.setWidth(img.getWidth(null));
            wh.setHeight(img.getHeight(null));

            //检查是否有旋转角度导致ImageIO获取宽高相反
            Metadata metadata = ImageMetadataReader.readMetadata(file);
            StringBuilder description = new StringBuilder();
            metadata.getDirectories().forEach(directory -> {
                directory.getTags().forEach(tag -> {
                    if (tag.getTagType() == ExifDirectoryBase.TAG_ORIENTATION) {
                        description.append(tag.getDescription().replaceAll(" ", ""));
                    }
                });
            });
            if (description.length() > 0) {
                int rotateIndex = description.indexOf("Rotate");
                int cwIndex = description.indexOf("CW");
                if (rotateIndex >= 0 && cwIndex > 0 && rotateIndex < cwIndex) {
                    int angel = Integer.parseInt(description.substring(rotateIndex + 6, cwIndex));
                    if (angel == 90 || angel == 180) {
                        //宽高互换
                        int t = wh.getHeight();
                        wh.setHeight(wh.getWidth());
                        wh.setWidth(t);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return wh;
    }

 

参考博文地址

https://www.bbsmax.com/A/E35p0je85v/

 

posted @ 2023-04-20 13:06  岑惜  阅读(302)  评论(0编辑  收藏  举报