I have here an black/white png file of the dimensions 2156x1728 which I want to rotate 90 degrees using AffineTransform. The resulting image doesn't have the right proportions. Here some example code (given I have successfully loaded the png file into the BufferedImage ):
public BufferedImage transform(BufferedImage image){
System.out.println("Input width: "+ image.getWidth());
System.out.println("Input height: "+ image.getHeight());
AffineTransform affineTransform = new AffineTransform();
affineTransform.setToQuadrantRotation(1, image.getWidth() / 2, image.getHeight() / 2);
AffineTransformOp opRotated = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage transformedImage = opRotated.createCompatibleDestImage(image, image.getColorModel());
System.out.println("Resulting width: "+ transformedImage.getWidth());
System.out.println("Resulting height: "+ transformedImage.getHeight());
transformedImage = opRotated.filter(image, transformedImage);
return transformedImage;
}
The output is accordingly:
Input width: 2156
Input height: 1728
Resulting width: 1942
Resulting height: 1942
How comes that the rotation returns such completely unrelated dimensions?
I'm not a pro at this, but why not just create a BufferedImage of the correct size? Also note that your center of revolution is incorrect. You will need to rotate over a center of [w/2, w/2] or [h/2, h/2] (w being width and h being height) depending on which quadrant you're rotating to, 1 or 3, and the relative height and width of the image. For instance:
Edit 1
You asked:
To explain this best, it's best to visualize and physically manipulate a rectangle:
Cut out rectangular piece of paper and place it on a piece of paper such that its upper left corner is on the upper left corner of the piece of paper -- that's your image on the screen. Now check to see where you would need to rotate that rectangle 1 or 3 quadrants so that its new upper left corner is overlying that of the paper, and you'll see why you need to use [w/2, w/2] or [h/2, h/2].
furykid's answer is great and helped me a lot. But it isn't so perfect. If the image is rectangular the resulting rotated image might contain some extra black pixels at one side.
I tried with a Marty Feldman photo, the original and the results can be viewed in this link: Marty Feldman rotation tests
It is difficult to see on a black background, but on any image editing software it is easy to see the little black border on the right and bottom side of the resulting images. This might not be a problem for some, but if it is for you, here's the fixed code(I kept the original as commentaries for easier comparison):
WARNING: Opinion ahead. I'm not sure of the reason why this happens but I have a guess. If you can explain better, please edit.
The above solution had problems with wdith & height of images the code below is independent of w > h || h > w