-2

Can you please comment this code? I understand some parts but not all.

This code is to rotate an image 90 degrees counter clockwise:

public static void rotate(String originalImage, String convertedImage) throws Exception {
    BufferedImage bufferImg = ImageIO.read(new File(originalImage));
    BufferedImage bufferImgOut = new BufferedImage(bufferImg.getWidth(),bufferImg.getHeight(), bufferImg.getType()); 
    for( int x = 0; x < bufferImg.getWidth(); x++ ) {
        for( int y = 0; y < bufferImg.getHeight(); y++ ) {
            int px = bufferImg.getRGB(x, y);
            int destY = bufferImg.getWidth() - x - 1; //what does this line do? 
            bufferImgOut.setRGB(y,destY, px);
        }
    }
    File outputfile = new File(convertedImage);
    ImageIO.write(bufferImgOut, "png", outputfile);
}
MaryAD
  • 41
  • 2
  • Basically since the Swing coordinate system starts with `y = 0` at the top, you have to flip the x coordinate to rotate. – Radiodef Jan 27 '14 at 21:59

1 Answers1

1

given the following axes

      y
      | o
-x ------- x
      |
     -y

to rotate an image you need to change axis from Y to X and from X to -Y

      y
      | 
-x ------- x
      | o
     -y

the code bufferImgOut.setRGB(y,destY, px); assigns every point (x,y) to (y,-x) then the code int destY = bufferImg.getWidth() - x - 1 represents the -x, but image doesn't support negative axes and then is translated again on the positive axis. The -1 is only due to java indexing (from 0 to width).

In other words:

y          x           x
| o        | o         | o
---- x     ---- -y     ---- y
original    (y, - x )   (y, Width() - x - 1)

I hope it helps

venergiac
  • 7,469
  • 2
  • 48
  • 70