Using java, how can I make a method taking in a BufferedImage, rotate it, and return a BufferedImage ( with correct width / height )

StackOverflow https://stackoverflow.com/questions/8290011

  •  10-03-2021
  •  | 
  •  

سؤال

I have been looking up a lot of examples, every time I try, my image becomes offset, and also not rotated by the degree I am looking for.

I have a class which extends JPanel, and draws an image. This JPanel is then put into my JFrame. I need to have a method, which when I click a button can take the image of the JPanel, rotate it, and return ( with the new height and width ). - Then I can ask the JPanel to repaint using the new image, and.. it should have rotated.

If someone could please help me with an example, of rotating 90 degrees, and returning with now the height = the old width, and width = old height, that would be amazing!

Thanks,

هل كانت مفيدة؟

المحلول

Here you are

Image rotatedImage = new BufferedImage(imageToRotate.getHeight(null), imageToRotate.getWidth(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) rotatedImage.getGraphics();
g2d.rotate(Math.toRadians(90.0));
g2d.drawImage(imageToRotate, 0, -rotatedImage.getWidth(null), null);
g2d.dispose();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top