How to save rotated buffered image in another buffered image?

假如想象 提交于 2019-12-14 03:59:53

问题


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;
 }

回答1:


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



来源:https://stackoverflow.com/questions/36395716/how-to-save-rotated-buffered-image-in-another-buffered-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!