我曾经搜过它,但我没有得到直截了当的回答。 我想要一个缓冲的图像旋转,但不要裁剪 我知道新的尺寸会是这样的事情
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)));
为我提供一种方法。
BTW有没有办法用JLabel
轮换ImageIcon
?
意图:添加到面板和分层窗格,并将其保存到文件(保存分层窗格)。
或者我们可以旋转分层窗格吗?
答案 0 :(得分:3)
如何在不裁剪的情况下旋转缓冲的图像?
通过计算轮换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;
}
以下是上述代码的测试示例:
答案 1 :(得分:0)
BT有没有办法用ImageIcon旋转JLabel?
更简单的方法是旋转图标,而不是标签。
查看Rotated Icon以查找执行旋转的类,并在旋转图标时重新计算图标的大小。
意图:添加到面板和分层窗格,并将其保存到文件(保存分层窗格)。
不确切地知道这意味着什么,但如果您只想保存分层窗格的“图像”,请查看Screen Image。