10

I am trying to rotate image. I am using this Java code:

BufferedImage oldImage = ImageIO.read(new FileInputStream("C:\\workspace\\test\\src\\10.JPG"));
BufferedImage newImage = new BufferedImage(oldImage.getHeight(), oldImage.getWidth(), oldImage.getType());
Graphics2D graphics = (Graphics2D) newImage.getGraphics();
graphics.rotate(Math.toRadians(90), newImage.getWidth() / 2, newImage.getHeight() / 2);
graphics.drawImage(oldImage, 0, 0, oldImage.getWidth(), oldImage.getHeight(), null);
ImageIO.write(newImage, "JPG", new FileOutputStream("C:\\workspace\\test\\src\\10_.JPG"));

But I see strange result:

Source:

**Sourse image:**

Result:

**Result image:**

Can you please help me with this problem?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
liosha
  • 103
  • 1
  • 1
  • 5
  • 3
    Shouldn't you rotate about the center of oldImage, rather than newImage? – Pete Fordham Aug 28 '12 at 19:18
  • I try graphics.rotate(Math.toRadians(90), oldImage.getWidth() / 2, oldImage.getHeight() / 2); Its not help. http://s13.postimage.org/7omxa1oef/image.jpg – liosha Aug 28 '12 at 19:22

4 Answers4

14

It is not enough to switch the width and height of the image. You are rotating using the center of the image as the origin of rotation. Just try the same with a sheet of paper and you will see it works the same way. You must also move the paper a little bit, which means to apply a transform to fix this. So, immediately after the rotate call, do this:

  graphics.translate((newImage.getWidth() - oldImage.getWidth()) / 2, (newImage.getHeight() - oldImage.getHeight()) / 2);
Dan D.
  • 32,246
  • 5
  • 63
  • 79
0

The new image has different sizes because of the rotate. try this: BufferedImage newImage = new BufferedImage( oldImage.getWidth(),oldImage.getHeight(),oldImage.getType());

0

Try getting bounds of your panel on which you do your drawing

Rectangle rect = this.getBounds();

And then do:

graphics.rotate(Math.toRadians(90), (rect.width - newImage.getWidth()) / 2, (rect.height - newImage.getHeight()) / 2);

Hope that could help Cheers!

java_xof
  • 439
  • 4
  • 16
0

You can write like this it will be work.

BufferedImage newImage = new BufferedImage(oldImage.getWidth(), oldImage.getHeight(), oldImage.getType());

I think the place for width and height is wrong in your code.

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68