Java: Rotating Images

AffineTransform instances can be concatenated (added together). Therefore you can have a transform that combines 'shift to origin', 'rotate' and 'shift back to desired position'.


I struggled a little with the existing answers because my image to be rotated is not always a square, furthermore the accepted answer has a comment asking "Any info on how to circumvent the cutoff problem" that is not answered. So for those who had the issue of image being croped when rotated here is the code that worked for me :

public static BufferedImage rotate(BufferedImage bimg, Double angle) {
    double sin = Math.abs(Math.sin(Math.toRadians(angle))),
           cos = Math.abs(Math.cos(Math.toRadians(angle)));
    int w = bimg.getWidth();
    int h = bimg.getHeight();
    int neww = (int) Math.floor(w*cos + h*sin),
        newh = (int) Math.floor(h*cos + w*sin);
    BufferedImage rotated = new BufferedImage(neww, newh, bimg.getType());
    Graphics2D graphic = rotated.createGraphics();
    graphic.translate((neww-w)/2, (newh-h)/2);
    graphic.rotate(Math.toRadians(angle), w/2, h/2);
    graphic.drawRenderedImage(bimg, null);
    graphic.dispose();
    return rotated;
}

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

A simple way to do it without the use of such a complicated draw statement:

    //Make a backup so that we can reset our graphics object after using it.
    AffineTransform backup = g2d.getTransform();
    //rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle
    //is the angle to rotate the image. If you want to rotate around the center of an image,
    //use the image's center x and y coordinates for rx and ry.
    AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry);
    //Set our Graphics2D object to the transform
    g2d.setTransform(a);
    //Draw our image like normal
    g2d.drawImage(image, x, y, null);
    //Reset our graphics object so we can draw with it again.
    g2d.setTransform(backup);