Wednesday, December 22, 2010

Rotate and translate images with AffineTransform

Staying on the same subject as my previous posts, the next example will help you rotate and translate any BufferedImage.

public BufferedImage rotateImage(BufferedImage rotateImage) {
AffineTransformOp op = null;

try {

   AffineTransform tx = new AffineTransform();

   //Rotate 90ยบ
   tx.rotate(Math.toRadians(90), rotateImage.getWidth()
              / 2.0, rotateImage.getHeight() / 2.0);

   AffineTransform translationTransform;
   translationTransform = findTranslation(tx, rotateImage);

   tx.preConcatenate(translationTransform);

   op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

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

   return op.filter(rotateImage, null);
}


The function that finds the Translation:

private AffineTransform findTranslation(AffineTransform at, BufferedImage bi) {
   Point2D p2din, p2dout;

   p2din = new Point2D.Double(0.0, 0.0);
   p2dout = at.transform(p2din, null);
   double ytrans = p2dout.getY();

   p2din = new Point2D.Double(0, bi.getHeight());
   p2dout = at.transform(p2din, null);
   double xtrans = p2dout.getX();

   AffineTransform tat = new AffineTransform();
   tat.translate(-xtrans, -ytrans);

   return tat;
}

And finally ... import this:
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

All done :)

No comments:

Post a Comment