[英]Saving png image with Java using JFileChooser
I am trying to save an image that is formed with a BufferedImage. 我正在尝试保存由BufferedImage形成的图像。 I get the BufferedImage by doing
我通过做得到BufferedImage
(BufferedImage) fg;
fg is an image of my jPanel's graphics. fg是我的jPanel图形的图像。 I am successful at saving the image by hardcoding the path in directly as follows:
通过将路径直接硬编码如下,我成功地保存了图像:
ImageIO.write((BufferedImage)fg,"png",new File("C:\\Users\\Geiger\\Documents\\test.png"));
But when I attempt to add the JFileChooser to the mix the image that is saved comes up being blank with nothing but the jPanel's background color. 但是,当我尝试将JFileChooser添加到混合图像时,保存的图像变成空白,除了jPanel的背景色。
My code for my attempt at utilizing the JFileChooser is as follows: 我尝试利用JFileChooser的代码如下:
JFileChooser jfc = new JFileChooser();
int retVal = jfc.showSaveDialog(null);
if(retVal==JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
String test = f.getAbsolutePath();
ImageIO.write((BufferedImage)fg,"png",new File(test));
}
EDIT:To clarify on the issue a little bit more: The issue is not that a file doesn't appear its that the graphics don't appear on the image when using the JFileChooser object. 编辑:要进一步澄清这个问题:问题不是文件没有出现,使用JFileChooser对象时图形没有出现在图像上。
I update my image when the JFrame has a mouse presses event: 当JFrame发生鼠标按下事件时,我会更新图像:
fg = jPanel2.createImage(jPanel2.getWidth(), jPanel2.getHeight());
try to put this line of code I think that's what you need: 尝试放入这一行代码,我认为这是您需要的:
ImageIO.write(buffer, "png", fileDialog.getSelectedFile());
Hope that helps 希望能有所帮助
Graphics2D graphics2D = image.createGraphics();
scribblePane.paint(graphics2D);
Use these two lines of code to add graphics. 使用这两行代码添加图形。
That's works for me 那对我有用
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("*.png", "png"));
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
ImageIO.write((BufferedImage) image, "png", new File(file.getAbsolutePath()));
} catch (IOException ex) {
System.out.println("Failed to save image!");
}
} else {
System.out.println("No file choosen!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.