java - 旋转内存中的图像

标签 java image rotation awt

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

最佳答案

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

正值将使图像顺时针旋转,负值则逆时针旋转。 生成的图像将调整大小,以便旋转后的图像完全适合它。
我已经使用 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;
}

关于java - 旋转内存中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13135590/

相关文章:

java - 高级 LCDS 主题的资源?

image - 如何下载 css-3 过滤器应用图像

image - Google+ 相册网址

image - openshift imagestream 不跟踪私有(private) docker 存储库

java - 如何逆时针旋转数组并将其垂直反转?

ios - Scenekit - SCNNode 的多次旋转和轴的方向

java - 添加 ImageView 会导致 Android 应用小部件崩溃

java - 我在这里使用父类(super class)构造函数调用是否有必要?

java - 无法将我的文件夹包含在可执行 .jar 文件中

java - 2个方向的3D旋转?