Java - Image Rotation

16,911

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);
Share:
16,911
liosha
Author by

liosha

Updated on June 15, 2022

Comments

  • liosha
    liosha almost 2 years

    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?

  • obataku
    obataku over 11 years
    I feel ashamed for not immediately thinking of this... :-p
  • java_xof
    java_xof over 11 years
    was late for a minute ... well :P