gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:54:22 24 4
gpt4 key购买 nike

我已经搜索过了,但没有得到直接的答案。我想要旋转缓冲图像但不裁剪我知道新维度会是这样的

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

给我一​​个方法。

顺便说一句,有没有办法用 ImageIcon 旋转 JLabel

意图:添加到面板和分层 Pane ,并将其保存到文件(保存分层 Pane )。

或者我们可以旋转分层 Pane 吗?

最佳答案

How to rotate a buffered image without cropping it?

通过计算旋转后的 BufferedImage 的大小,您已经完成了一半的工作。另一半实际上是创建旋转的 BufferedImage。您可以使用 Graphics2D 来做到这一点并在将原始图像绘制到新图像之前应用一些坐标变换。此外,用一些背景颜色绘制“多余”区域是有意义的。

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

下面是上述代码的测试示例:

原图
original

旋转图像(30度)
rotated

关于java - 如何在不裁剪的情况下旋转缓冲图像?有没有办法旋转 JLayeredPane 或 JLabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com