Java图像处理:实现图像旋转功能
/**
-
图像处理类,提供图像旋转功能 */ class ImageProcessor {
/**
-
旋转图像
-
@param image 要旋转的图像
-
@param angle 旋转角度(顺时针方向) */ public void rotate(Image image, int angle) { // 获取图像宽度和高度 int width = image.getWidth(null); int height = image.getHeight(null);
// 计算旋转后的图像宽度和高度 double radians = Math.toRadians(angle); double sin = Math.abs(Math.sin(radians)); double cos = Math.abs(Math.cos(radians)); int newWidth = (int) Math.round(width * cos + height * sin); int newHeight = (int) Math.round(height * cos + width * sin);
// 创建旋转后的图像 BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = rotatedImage.createGraphics(); g2d.translate((newWidth - width) / 2, (newHeight - height) / 2); g2d.rotate(radians, width / 2, height / 2); g2d.drawRenderedImage((RenderedImage) image, null); g2d.dispose();
// 更新原图像 image = rotatedImage; } }
-
原文地址: https://www.cveoy.top/t/topic/f1q4 著作权归作者所有。请勿转载和采集!