且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不裁剪的情况下旋转缓冲图像?有没有办法旋转JLayeredPane或JLabel?

更新时间:2022-11-03 15:40:00


如何旋转缓冲的图像而不对其进行裁剪?


通过计算旋转的 BufferedImage $ c $的大小,你已经完成了一半的工作C>。
另一半实际上是创建了旋转的 BufferedImage
您可以使用



旋转图像(30度)


I had searched about it but I did not get straight forward answer. I want a buffered image to be rotated but not cropped I knew the new dimensions are gonna be some thing like this

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

Provide me a method for that.

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

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

Or can we rotate the layered pane?

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)