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/
本文来自博客园,作者:岑惜,转载请注明原文链接:https://www.cnblogs.com/c2g5201314/p/17336425.html
响应开源精神相互学习,内容良币驱除劣币