Search code examples
javaimageswingrotationgraphics2d

Rotate 90 degree to right image in java


I can not rotate image 90 degree to right . I need to be able to rotate images individually in java. The only thing. Unfortunately, I need to draw the image at a specific point, and there is no method with an argument that 1.rotates the image separately and 2. allows me to set the x and y. any help is appreciated

public class Tumbler extends GraphicsProgram{

public void run() {
    setSize(1000,1000);
    GImage original = new GImage("sunset.jpg");
    add(original, 10, 10);
    int[][] pixels = original.getPixelArray();
    int height = pixels.length;
    int width = pixels[0].length;

    // Your code starts here
    int newheight = width;
    int newwidth = height;
    int[][] newpixels = new int[newheight][newwidth];

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {               
            newpixels[j][height-1-i] = pixels[i][j];            
        }
    }


    GImage image = new GImage(newpixels);
    add(image, width+20, 10);

    // Your code ends here
    }

Solution

  • As discussed here, you can use AffineTransformOp to rotate an image by Math.PI / 2; this is equivalent to rotating the image clockwise 90°, as shown here. See also Handling 90-Degree Rotations.