The next function will rotate the buffered image, which comes undefined if it is a perfect square or not.
public BufferedImage rotate(BufferedImage image) { AffineTransform xform = new AffineTransform(); if (image.getWidth() > image.getHeight()) { xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getWidth()); xform.rotate(_theta); int diff = image.getWidth() - image.getHeight(); switch (_thetaInDegrees) { case 90: xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff); break; case 180: xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff); break; default: xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth()); break; } } else if (image.getHeight() > image.getWidth()) { xform.setToTranslation(0.5 * image.getHeight(), 0.5 * image.getHeight()); xform.rotate(_theta); int diff = image.getHeight() - image.getWidth(); switch (_thetaInDegrees) { case 180: xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight()); break; case 270: xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight()); break; default: xform.translate(-0.5 * image.getHeight(), -0.5 * image.getHeight()); break; } } else { xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getHeight()); xform.rotate(_theta); xform.translate(-0.5 * image.getHeight(), -0.5 * image.getWidth()); } AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_BILINEAR); BufferedImage newImage =new BufferedImage(image.getHeight(), image.getWidth(), image.getType()); return op.filter(image, newImage); }
source share