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();
}