java 如何旋转图片
旋转图片的方法
在Java中旋转图片可以通过多种方式实现,以下是几种常见的方法:

使用AffineTransform和Graphics2D
Java的Graphics2D类结合AffineTransform可以实现图片旋转。以下是一个示例代码:

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageRotator {
public static BufferedImage rotateImage(BufferedImage image, double angle) {
double radians = Math.toRadians(angle);
double sin = Math.abs(Math.sin(radians));
double cos = Math.abs(Math.cos(radians));
int newWidth = (int) Math.round(image.getWidth() * cos + image.getHeight() * sin);
int newHeight = (int) Math.round(image.getHeight() * cos + image.getWidth() * sin);
BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotated.createGraphics();
AffineTransform transform = new AffineTransform();
transform.translate((newWidth - image.getWidth()) / 2, (newHeight - image.getHeight()) / 2);
transform.rotate(radians, image.getWidth() / 2, image.getHeight() / 2);
g2d.setTransform(transform);
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return rotated;
}
public static void main(String[] args) throws Exception {
BufferedImage original = ImageIO.read(new File("input.jpg"));
BufferedImage rotated = rotateImage(original, 45);
ImageIO.write(rotated, "jpg", new File("output.jpg"));
}
}
使用Thumbnailator库
Thumbnailator是一个简化图像处理的库,可以轻松实现旋转功能:
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
public class ThumbnailatorRotate {
public static void main(String[] args) throws Exception {
Thumbnails.of(new File("input.jpg"))
.scale(1)
.rotate(90)
.toFile(new File("output.jpg"));
}
}
使用OpenCV
如果项目已集成OpenCV,可以使用其旋转功能:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class OpenCVRotate {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread("input.jpg");
Mat dst = new Mat();
Mat rotationMatrix = Imgproc.getRotationMatrix2D(
new org.opencv.core.Point(src.cols()/2, src.rows()/2), 45, 1);
Imgproc.warpAffine(src, dst, rotationMatrix, src.size());
Imgcodecs.imwrite("output.jpg", dst);
}
}
注意事项
- 旋转角度以度为单位,顺时针方向为正方向。
- 旋转后图片尺寸可能会变化,需要计算新尺寸以避免裁剪。
- 对于大图片,注意内存消耗和处理时间。
- 某些格式(如JPEG)旋转可能导致质量损失,建议使用无损格式(如PNG)进行处理。






