我已经搜索过,但没有得到直接的答案。
我想要旋转但不裁剪缓冲图像
我知道新的维度会是这样的
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)));
给我一个方法。
顺便说一句,有什么办法可以旋转JLabel
与ImageIcon
?
意图:添加到面板和分层窗格并将其保存到文件(保存分层窗格)。
或者我们可以旋转分层窗格吗?
如何旋转缓冲图像而不裁剪它?
通过计算旋转的大小,您已经完成了一半的工作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 image
Rotated image (by 30 degree)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)