Rotating BufferedImage instances

user577304 picture user577304 · Feb 7, 2011 · Viewed 54.7k times · Source

I am having trouble getting a rotated BufferedImage to display. I think the rotation is working just fine, but I can't actually draw it to the screen. My code:

Class extends JPanel {
    BufferedImage img;
    int rotation = 0;

    public void paintComponent(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight());
        img2d = img.createGraphics();
        img2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);
        g.drawImage(img, imgx, imgy, null);
        this.repaint();
    }
}

This is not working for me. I could not find any way to draw the rotated img2d onto g.

EDIT: I have multiple objects that are being drawn onto g, so I can't rotate that. I need to be able to rotate things individually.

Answer

Harry Joy picture Harry Joy · Feb 7, 2011

Maybe you should try using AffineTransform like this:

    AffineTransform transform = new AffineTransform();
    transform.rotate(radians, bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);
    AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
    bufferedImage = op.filter(bufferedImage, null);

Hope this helps.