我在内存中保存了一个 java.Awt 图像列表,并且需要旋转它们。我读过一些解决方案,但它们涉及改变图像的显示方式,而不是真正旋转图像本身。 我需要旋转图像本身,而不是以旋转的方式绘制。如何才能实现这一目标?
最佳答案
以下代码会将图像旋转任意角度(以度为单位)。
正值度
将使图像顺时针旋转,负值则逆时针旋转。
生成的图像将调整大小,以便旋转后的图像完全适合它。
我已经使用 jpg
和 png
图像文件作为输入对其进行了测试。
public static BufferedImage rotateImage(BufferedImage src, double degrees) {
double radians = Math.toRadians(degrees);
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
/*
* Calculate new image dimensions
*/
double sin = Math.abs(Math.sin(radians));
double cos = Math.abs(Math.cos(radians));
int newWidth = (int) Math.floor(srcWidth * cos + srcHeight * sin);
int newHeight = (int) Math.floor(srcHeight * cos + srcWidth * sin);
/*
* Create new image and rotate it
*/
BufferedImage result = new BufferedImage(newWidth, newHeight,
src.getType());
Graphics2D g = result.createGraphics();
g.translate((newWidth - srcWidth) / 2, (newHeight - srcHeight) / 2);
g.rotate(radians, srcWidth / 2, srcHeight / 2);
g.drawRenderedImage(src, null);
return result;
}
关于java - 旋转内存中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13135590/