这是由于手机拍摄图片的时候,会将方向等信息写入图片的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());
}
}