Thursday, January 13, 2011

How to read, rotate and save images with Graphics2D

My previous post "Rotate and translate images with AffineTransformrotates and translates any buffered image, however I found out that using AffineTransform isn't always the best solution. I've encountered several problems rotating images bigger than 2000px and because of that, another solution was needed to resolve my problem.

Here's a little example that reads and rotates an image 90 degrees.
private String rotateImage(String pathToImage) {

BufferedImage image = null;
String tempFileName = null;

try {
   File f = new File(pathToImage);

   if (f.exists()) {

     image = ImageIO.read(f);

     Image rotatedImage = new BufferedImage(image.getHeight(),
                      image.getWidth(),image.getType());

     Graphics2D g2d = (Graphics2D) rotatedImage.getGraphics();

     g2d.rotate(Math.toRadians(90.0));

     g2d.drawImage(image, 0, -rotatedImage.getWidth(null), null);
     g2d.dispose();

     //Random name
     String timeStampName = UUID.randomUUID().
                           toString().substring(1, 8);

     //Save image to java.io.tmpdir
     tempFileName = System.getProperty("java.io.tmpdir") +
                    timeStampName + ".jpg";


     ImageIO.write((BufferedImage) rotatedImage, "jpg",
                                    new File(tempFileName));


   }

} catch (Exception e) {
  //TODO: Do something here
}

return tempFileName;

}

2 comments:

  1. Your code example change the type of the target image. Isn't it better to use the source image type for the target one?

    Image rotatedImage = new BufferedImage(image.getHeight(),
    image.getWidth(), image.getType());

    ReplyDelete
  2. Yes, you are correct :)
    I was using this example and I should have corrected that since this issue was already mentioned before in previous posts :)
    Thanks for the feedback.

    ReplyDelete