在内存中旋转图像

时间:2012-10-30 08:59:55

标签: java image rotation awt

我在内存中保留了java.Awt图像的列表,并且需要旋转它们。我已经阅读了一些解决方案,但它们涉及改变图像的显示方式,而不是真正旋转图像本身。 我需要自己旋转图像,而不是以旋转的方式绘制。如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

以下代码将以度为单位旋转任意角度的图像。

degrees的正值将顺时针旋转图像,逆时针旋转负值。 将调整生成的图像的大小,以便旋转的图像完全适合它 我已使用jpgpng图像文件作为输入对其进行了测试。

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;
}
相关问题