I am trying to rotate a buffered Image
and return the buffered Image
(rotated image) using getImage()
method. Rotation of image is happening but while saving it save the image as such without rotation of image.
Initialization:
private BufferedImage transparentImage;
PaintComponent:
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(RotationOfImage.value));
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(transparentImage, at, null);
repaint();
A method to return the rotated buffered Image.
public BufferedImage getImage(){
return transparentImage;
}
Basically, you're rotating the Graphics
context of the component and painting the image to it, which will have no effect on the original image.
Instead, you should be rotating the image and the painting it, for example...
public BufferedImage rotateImage() {
double rads = Math.toRadians(RotationOfImage.value);
double sin = Math.abs(Math.sin(rads));
double cos = Math.abs(Math.cos(rads));
int w = transparentImage.getWidth();
int h = transparentImage.getHeight();
int newWidth = (int) Math.floor(w * cos + h * sin);
int newHeight = (int) Math.floor(h * cos + w * sin);
BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotated.createGraphics();
AffineTransform at = new AffineTransform();
at.translate((newWidth - w) / 2, (newHeight - h) / 2);
at.rotate(Math.toRadians(RotationOfImage.value), w / 2, h / 2);
g2d.setTransform(at);
g2d.drawImage(transparentImage, 0, 0, this);
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
g2d.dispose();
}
Then you could paint it doing something like...
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
BufferedImage rotated = rotateImage();
int x = (getWidth() - rotated.getWidth()) / 2;
int y = (getHeight() - rotated.getHeight()) / 2;
g2d.drawImage(rotated, x, y, this);
g2d.dispose();
}
Now, you could optimise this, so you only generate a rotated version of the image when the angle has changed, but I'll leave that up to you
ps- I've not tested this, but it's based on this question