Java读取一张图片,打印出宽度和高度,我用软件查看这个图是横向的,但是用下面的程序打印出来却是宽度和高度却相反的,代码如下:
BufferedImage originalImage = ImageIO.read(new File(inputPath)); System.out.println("originalImage width, height: " + originalImage.getWidth() + ", " + originalImage.getHeight());
可能是因为图像的元数据中的旋转信息。许多图像文件,特别是从相机或手机拍摄的照片,会包含元数据(Exif数据),其中记录了图像的旋转信息。软件通常会根据这个元数据自动旋转图像,以正确显示它。但是,ImageIO.read
方法读取图像时,不会考虑这些旋转信息,这就导致了图像的宽度和高度可能与你预期的不一致。
为了验证和解决这个问题,你可以手动检查和处理图像的旋转信息,代码如下:
public static void main(String[] args) throws Exception { String inputPath = "path_to_your_image.jpg"; // 读取图像文件 BufferedImage originalImage = ImageIO.read(new File(inputPath)); // 获取图像的元数据 com.drew.metadata.Metadata metadata = ImageMetadataReader.readMetadata(new File(inputPath)); Directory directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class); int orientation = 1; // 默认值(1表示没有旋转) if (directory != null && directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) { orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION); } // 根据元数据旋转图像 BufferedImage rotatedImage = null; switch (orientation) { case 6: // 90 degrees CW rotatedImage = rotateImage(originalImage, 90); break; case 3: // 180 degrees rotatedImage = rotateImage(originalImage, 180); break; case 8: // 90 degrees CCW rotatedImage = rotateImage(originalImage, 270); break; default: rotatedImage = originalImage; break; } System.out.println("rotatedImage width, height: " + rotatedImage.getWidth() + ", " + rotatedImage.getHeight()); } // 旋转图像的方法 public static BufferedImage rotateImage(BufferedImage originalImage, int angle) { int width = originalImage.getWidth(); int height = originalImage.getHeight(); BufferedImage rotatedImage = new BufferedImage(height, width, originalImage.getType()); Graphics2D g2d = rotatedImage.createGraphics(); g2d.translate((height - width) / 2, (height - width) / 2); g2d.rotate(Math.toRadians(angle), height / 2, width / 2); g2d.drawRenderedImage(originalImage, null); g2d.dispose(); return rotatedImage; }
上面的代码使用第三方库, metadata-extractor
来读取Exif数据。需要增加pom依赖:
<dependency> <groupId>com.drewnoakes</groupId> <artifactId>metadata-extractor</artifactId> <version>2.16.0</version> </dependency>
文章评论