我正在创建一个 GUI,它将保存用户在 JLabel 上绘制的图像。这是我的 saveImage 方法的代码。我可以弹出该框,以便我可以选择保存文件的位置,但实际上没有保存文件。
public void saveImage()
{
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D image2 = image.createGraphics();
image2.setBackground(Color.WHITE);
image2.clearRect(0, 0, this.getWidth(), this.getHeight());
this.paintAll(image2);
try
{
File output = new File("rectangle.png");
ImageIO.write(image, "Rectangles", output);
final JFileChooser fchooser = new JFileChooser(".");
int retvalue = fchooser.showSaveDialog(RectangleLabel.this);
if (retvalue == JFileChooser.APPROVE_OPTION)
{
fchooser.setSelectedFile(output);
File f = fchooser.getSelectedFile();
}
}
catch(IOException ie)
{
}
}
最佳答案
首先,您需要创建组件的图像...
BufferedImage img = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
label.printAll(g2d);
g2d.dispose();
然后你需要保存它...
ImageIO.write(img, "png", f);
看看Writing/Saving an Image了解更多详情
关于java - 如何从 JLabel 保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161550/