-1
public void rotateImage90(){
    this.redisplayImage();

    for (int x = 0; x < this.image.length; x++)
        for (int y = 0; y < this.image[0].length; y++){
            this.image[x][y] = this.image[this.image.length-1-x][y];
    }
}

I dont know what to do from here to rotate an image 90 degrees. Please help if u can

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Max M
  • 1
  • 2
    Think about what happens for one single pixel. And what you have to consider when rotating non-square images. – Valerij Dobler Jun 01 '22 at 10:28
  • Does this answer your question? [Rotating a NxN matrix in Java](https://stackoverflow.com/questions/25882480/rotating-a-nxn-matrix-in-java) – kotatsuyaki Jun 02 '22 at 11:40

1 Answers1

0

Here is one way to do it. There may be better ways using an AffineTransForm. This method does not explicitly rotate the source image but rotates the target graphics context, and then writes the image to that.

  • read in the source image. In this case into buf.
  • extract the dimensions.
  • create the target rotated BufferedImage (output) reversing the source dimensions and copying the image type (JPEG, PNG, etc).
  • Now get the graphics context for the output image.
  • Since you want to rotate about the center, translate to the target center anchors and then rotate in radians to 90 degrees (Math.PI/2).
  • Now get ready to write the source image (buf) into the rotated context of (output). However, the anchors need to be retranslated to the starting position for the source file (buf). So translate back but reverse the width and height anchors to match the width and height of the source file.
  • then draw the original image (buf) into the context rotated buffered image (output).
  • And write the rotated image (output) to the file system

try {
    BufferedImage buf =
            ImageIO.read(new File("f:/sourceImage.jpg"));
    int width = buf.getWidth();
    int height = buf.getHeight();
    BufferedImage output = new BufferedImage(height, width, buf.getType());
    
    Graphics2D g2d = (Graphics2D)output.getGraphics();
    g2d.translate(height/2., width/2.);
    g2d.rotate(Math.PI/2);
    g2d.translate(-width/2., -height/2.);
    g2d.drawImage(buf, 0,0,width, height,null);
    ImageIO.write(output, "JPEG", new File("f:/rotatedImage.jpg"));
} catch (Exception e) {
    e.printStackTrace();
}
WJS
  • 36,363
  • 4
  • 24
  • 39