[英]How to save an Image from a JLabel
I am working to create a GUI that will save an Image drawn on a JLabel by a user. 我正在创建一个GUI,用于保存用户在JLabel上绘制的图像。 Here is the code that I have for my saveImage method. 这是我的saveImage方法的代码。 I can get the box to pop up so that I can select where to save the file, but no file is actually saved. 我可以弹出框以便我可以选择保存文件的位置,但实际上没有文件保存。
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)
{
}
}
First, you need to create an image of the component... 首先,您需要创建组件的图像...
BufferedImage img = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
label.printAll(g2d);
g2d.dispose();
Then you need to save it... 然后你需要保存它......
ImageIO.write(img, "png", f);
Take a look at Writing/Saving an Image for more details 有关详细信息,请参阅编写/保存图像
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.