在Java中将图像旋转90度

10

我已经成功将一张图片旋转了180度,但是我希望将其顺时针90度旋转,请问有谁能编辑我的代码并解释一下。谢谢。

 private void rotateClockwise()
    {
        if(currentImage != null){
            int width = currentImage.getWidth();
            int height = currentImage.getHeight();
            OFImage newImage = new OFImage(width, height);
            for(int y = 0; y < height; y++) {
                for(int x = 0; x < width; x++) {
                    newImage.setPixel( x, height-y-1, currentImage.getPixel(x, y));
                }
        }
            currentImage = newImage;
            imagePanel.setImage(currentImage);
            frame.pack();
    }
    }

1
尝试思考当您旋转图像的每个象限时会发生什么。我认为这应该是一个不错的方法。分别解决每个象限。 - Renato Lochetti
3
example - Vignesh Vino
感谢Vignesh Vino提供的示例,我成功让它工作了,非常感激。 - Ryan Gibson
你需要交换x和y。我会把这个作为答案,但是不能。OFImage newImage = new OFImage(height, width); newImage.setPixel(height-1-y, x, currentImage.getPixel(x, y)); - user2426985
2个回答

13

使用这个方法。

/**
 * Rotates an image. Actually rotates a new copy of the image.
 * 
 * @param img The image to be rotated
 * @param angle The angle in degrees
 * @return The rotated image
 */
public static Image rotate(Image img, double angle)
{
    double sin = Math.abs(Math.sin(Math.toRadians(angle))),
           cos = Math.abs(Math.cos(Math.toRadians(angle)));

    int w = img.getWidth(null), h = img.getHeight(null);

    int neww = (int) Math.floor(w*cos + h*sin),
        newh = (int) Math.floor(h*cos + w*sin);

    BufferedImage bimg = toBufferedImage(getEmptyImage(neww, newh));
    Graphics2D g = bimg.createGraphics();

    g.translate((neww-w)/2, (newh-h)/2);
    g.rotate(Math.toRadians(angle), w/2, h/2);
    g.drawRenderedImage(toBufferedImage(img), null);
    g.dispose();

    return toImage(bimg);
}

这段内容取自于我的ImageTool类。

希望它能对你有所帮助。


为什么你复制了这张图片,难道不能通过在绘制时应用90度旋转的仿射变换来完成吗?请澄清一下。 - Mihir
@Mihir 那是我的游戏的要求。这个类来自我的游戏引擎,所以我使用了它。你可以使用任何你喜欢的东西。 - Sri Harsha Chilakapati
我实际上不得不创建一个新的缓冲图像。否则,我会得到意外的结果。 - juminoz
据我所理解,这段代码是顺时针旋转的,请问如何逆时针旋转呢? - Noosrep
是的,我也这么想,但你的代码可以运行,所以我以为你可能遇到了同样的问题。缓存只是一个猜测,但我会发布一个新的问题。 - Noosrep
显示剩余8条评论


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接