How to rotate a buffered image without cropping it? Is there any way to rotate a JLayeredPane or JLabel?

折月煮酒 提交于 2019-12-06 13:21:33

How to rotate a buffered image without cropping it?

You had already half of the work by calculating the size of the rotated BufferedImage. The other half is actually creating the rotated BufferedImage. You can do that by using Graphics2D and applying some coordinate transformations before drawing the original image onto the new one. Furthermore, it makes sense to paint the "excess" area with some background color.

public BufferedImage rotateImage(BufferedImage originalImage, double degree) {
    int w = originalImage.getWidth();
    int h = originalImage.getHeight();
    double toRad = Math.toRadians(degree);
    int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad)));
    int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad)));

    BufferedImage rotatedImage = new BufferedImage(wPrime, hPrime, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = rotatedImage.createGraphics();
    g.setColor(Color.LIGHT_GRAY);
    g.fillRect(0, 0, wPrime, hPrime);  // fill entire area
    g.translate(wPrime/2, hPrime/2);
    g.rotate(toRad);
    g.translate(-w/2, -h/2);
    g.drawImage(originalImage, 0, 0, null);
    g.dispose();  // release used resources before g is garbage-collected
    return rotatedImage;
}

Here is a test example from the above code:

Original image

Rotated image (by 30 degree)

BTW is there any way to rotate a JLabel with an ImageIcon?

The easier way is to rotate the Icon, not the label.

Check out Rotated Icon for a class that does the rotation and recalculates the size of the Icon as it is rotated.

Intention: adding to panels and layered pane and also saving it to file (saving the layered pane).

Don't know exactly what that means, but if you just want to save an "image" of the layered pane then check out Screen Image.

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