0

I am looking to rotate an image that is loaded from files by 90 degrees. I have the code but when I use it, I am given an error saying that the coordinates are out of bounds. Any help would be appreciated.

Here is the method I have written so far:

public void rotateImage(OFImage image) {
    if (currentImage != null) {
        int width = image.getWidth();
        int height = image.getHeight();
        OFImage newImage = new OFImage(width, height);

        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Color col = image.getPixel(i, j);
                newImage.setPixel(height - j - 2, i, col);
            }
        }
        image = newImage;
    }
}
Amir Dora.
  • 2,831
  • 4
  • 40
  • 61

1 Answers1

0

When you rotate the image by a certain angle, the resulting image becomes larger than the original one. The maximum image size is obtained when rotated by 45 degrees:

rotated and non-rotated image

When creating a new image, you have to set its dimensions according to the rotated size:

public BufferedImage rotateImage(BufferedImage image, double angle) {
    double radian = Math.toRadians(angle);
    double sin = Math.abs(Math.sin(radian));
    double cos = Math.abs(Math.cos(radian));

    int width = image.getWidth();
    int height = image.getHeight();

    int nWidth = (int) Math.floor((double) width * cos + (double) height * sin);
    int nHeight = (int) Math.floor((double) height * cos + (double) width * sin);

    BufferedImage rotatedImage = new BufferedImage(
            nWidth, nHeight, BufferedImage.TYPE_INT_ARGB);

    // and so on...

    return rotatedImage;
}

See also: Rotate a buffered image in Java