java 判断图片否旋转_java获取图片朝向并旋转
时间: 2023-12-18 20:05:44 浏览: 178
在Java中,可以使用ImageIO类读取图片信息,包括图片的朝向信息。根据朝向信息,可以使用Java Graphics2D类进行旋转操作。
以下是一个示例代码,可以读取图片信息并进行旋转操作:
```java
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageRotationExample {
public static void main(String[] args) {
try {
// 读取图片
File inputFile = new File("input.jpg");
BufferedImage inputImage = ImageIO.read(inputFile);
// 获取朝向信息,如果有朝向信息则旋转图片
int orientation = getOrientation(inputImage);
BufferedImage outputImage = inputImage;
if (orientation != 1) {
outputImage = rotateImage(inputImage, orientation);
}
// 保存旋转后的图片
File outputFile = new File("output.jpg");
ImageIO.write(outputImage, "jpg", outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取图片朝向信息
public static int getOrientation(BufferedImage image) {
int orientation = 1;
try {
Object value = image.getProperty("orientation");
if (value != null) {
orientation = (Integer) value;
}
} catch (Exception e) {
e.printStackTrace();
}
return orientation;
}
// 旋转图片
public static BufferedImage rotateImage(BufferedImage image, int orientation) {
int width = image.getWidth();
int height = image.getHeight();
AffineTransform transform = new AffineTransform();
switch (orientation) {
case 2:
transform = AffineTransform.getScaleInstance(-1, 1);
transform.translate(-width, 0);
break;
case 3:
transform = AffineTransform.getRotateInstance(Math.PI, width / 2, height / 2);
break;
case 4:
transform = AffineTransform.getScaleInstance(1, -1);
transform.translate(0, -height);
break;
case 5:
transform = AffineTransform.getScaleInstance(-1, 1);
transform.translate(-width, 0);
transform.rotate(Math.toRadians(90), width / 2, height / 2);
break;
case 6:
transform = AffineTransform.getRotateInstance(Math.toRadians(90), width / 2, height / 2);
break;
case 7:
transform = AffineTransform.getScaleInstance(-1, 1);
transform.translate(-width, 0);
transform.rotate(Math.toRadians(-90), width / 2, height / 2);
break;
case 8:
transform = AffineTransform.getRotateInstance(Math.toRadians(-90), width / 2, height / 2);
break;
default:
break;
}
BufferedImage rotatedImage = new BufferedImage(width, height, image.getType());
Graphics2D graphics = rotatedImage.createGraphics();
graphics.drawImage(image, transform, null);
graphics.dispose();
return rotatedImage;
}
}
```
在该示例代码中,getOrientation()方法用于获取图片的朝向信息,rotateImage()方法用于旋转图片。在rotateImage()方法中,根据不同的朝向信息,使用AffineTransform类进行旋转操作。最后,使用Graphics2D类将旋转后的图片绘制到新的BufferedImage对象中。
阅读全文