Java 如何在另一个缓冲图像中保存旋转的缓冲图像?
我正在尝试旋转缓冲的Java 如何在另一个缓冲图像中保存旋转的缓冲图像?,java,swing,graphics,Java,Swing,Graphics,我正在尝试旋转缓冲的图像,并使用getImage()方法返回缓冲的图像(旋转图像)。正在进行图像旋转,但在保存图像时,不旋转图像即可保存图像 初始化: private BufferedImage transparentImage; 油漆组件: AffineTransform at = new AffineTransform(); at.rotate(Math.toRadians(RotationOfImage.value)); Graphics2D g2d = (Graphics2D) g;
图像
,并使用getImage()
方法返回缓冲的图像
(旋转图像)。正在进行图像旋转,但在保存图像时,不旋转图像即可保存图像
初始化:
private BufferedImage transparentImage;
油漆组件:
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(RotationOfImage.value));
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(transparentImage, at, null);
repaint();
返回旋转缓冲图像的方法
public BufferedImage getImage(){
return transparentImage;
}
基本上,您正在旋转组件的
图形上下文并向其绘制图像,这对原始图像没有影响
相反,你应该旋转图像并绘制它,例如
public BufferedImage rotateImage() {
double rads = Math.toRadians(RotationOfImage.value);
double sin = Math.abs(Math.sin(rads));
double cos = Math.abs(Math.cos(rads));
int w = transparentImage.getWidth();
int h = transparentImage.getHeight();
int newWidth = (int) Math.floor(w * cos + h * sin);
int newHeight = (int) Math.floor(h * cos + w * sin);
BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotated.createGraphics();
AffineTransform at = new AffineTransform();
at.translate((newWidth - w) / 2, (newHeight - h) / 2);
at.rotate(Math.toRadians(RotationOfImage.value), w / 2, h / 2);
g2d.setTransform(at);
g2d.drawImage(transparentImage, 0, 0, this);
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
g2d.dispose();
}
然后你可以把它画成
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
BufferedImage rotated = rotateImage();
int x = (getWidth() - rotated.getWidth()) / 2;
int y = (getHeight() - rotated.getHeight()) / 2;
g2d.drawImage(rotated, x, y, this);
g2d.dispose();
}
现在,你可以对此进行优化,这样你只会在角度改变时生成一个旋转版本的图像,但我会让你自己决定
ps-我没有测试过这个,但它是基于这个为什么要在paintComponent
中旋转它?你应该画旋转的图像。这样做不会对图像产生任何影响,因为您正在旋转组件“ps-我没有测试过这个…”Pfft的图形上下文。。你这样做过多少次?我肯定我能回忆起在这个网站上看到过至少3次(我的记忆力很差)。@AndrewThompson因为我从库代码中复制了算法,人们希望它能起作用:PMeh。。BNI…;-)哦,如果代码中出现了一些小故障,而这些故障只出现在极少数情况下,那么有什么更好的媒介(比如此)来发现并修复这种情况呢?