我想使用Java自动旋转图像,但发现错误
java.lang.NullPointerException方向= exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
我不知道如何修复代码,将图片另存为原始文件
File imageFile = new File(inFilePath);
BufferedImage originalImage = ImageIO.read(imageFile);
Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
ExifIFD0Directory exifIFD0Directory = metadata.getDirectory(ExifIFD0Directory.class);
JpegDirectory jpegDirectory = (JpegDirectory)metadata.getDirectory(JpegDirectory.class);
int orientation = 1;
try {
orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(orientation);
int width = jpegDirectory.getImageWidth();
int height = jpegDirectory.getImageHeight();
AffineTransform affineTransform = new AffineTransform();
BufferedImage bimg = ImageIO.read(imageFile);
switch (orientation) {
case 1:
break;
case 2: // Flip X
affineTransform.scale(-1.0, 1.0);
affineTransform.translate(-width, 0);
break;
case 3: // PI rotation
affineTransform.translate(width, height);
affineTransform.rotate(Math.PI);
break;
case 4: // Flip Y
affineTransform.scale(1.0, -1.0);
affineTransform.translate(0, -height);
break;
case 5: // - PI/2 and Flip X
affineTransform.rotate(-Math.PI / 2);
affineTransform.scale(-1.0, 1.0);
break;
case 6: // -PI/2 and -width
affineTransform.translate(height, 0);
affineTransform.rotate(Math.PI / 2);
break;
case 7: // PI/2 and Flip
affineTransform.scale(-1.0, 1.0);
affineTransform.translate(-height, 0);
affineTransform.translate(0, width);
affineTransform.rotate(3 * Math.PI / 2);
break;
case 8: // PI / 2
affineTransform.translate(0, width);
affineTransform.rotate(3 * Math.PI / 2);
break;
default:
break;
}
AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage destinationImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), originalImage.getType());
destinationImage = affineTransformOp.filter(originalImage, destinationImage);
ImageIO.write(destinationImage, "jpg", new File(inFilePath));