ImageIO实现图片旋转
时间: 2024-05-15 07:13:53 浏览: 122
实现图片旋转
使用ImageIO对图片进行旋转可以通过以下步骤实现:
1. 使用ImageIO读取原始图片
```java
File imageFile = new File("image.jpg");
BufferedImage originalImage = ImageIO.read(imageFile);
```
2. 创建一个新的BufferedImage对象,并将原始图片绘制到其中
```java
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.PI / 2, height / 2, width / 2);
g2d.drawRenderedImage(originalImage, null);
g2d.dispose();
```
3. 使用ImageIO将旋转后的图像保存到指定的文件中
```java
File rotatedImageFile = new File("rotated_image.jpg");
ImageIO.write(rotatedImage, "jpg", rotatedImageFile);
```
完整代码示例:
```java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageRotationExample {
public static void main(String[] args) {
try {
// 读取原始图片
File imageFile = new File("image.jpg");
BufferedImage originalImage = ImageIO.read(imageFile);
// 创建一个新的BufferedImage对象,并将原始图片绘制到其中
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.PI / 2, height / 2, width / 2);
g2d.drawRenderedImage(originalImage, null);
g2d.dispose();
// 将旋转后的图像保存到指定的文件中
File rotatedImageFile = new File("rotated_image.jpg");
ImageIO.write(rotatedImage, "jpg", rotatedImageFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
注意:在实际使用中,可能需要根据具体的需求进行调整。例如,可以通过修改绘制时的坐标和旋转角度来实现不同角度的旋转,并根据需要将其保存为不同格式的图像文件。
阅读全文