Java – Saving png image with Java using JFileChooser


I am trying to save an image that is formed with a BufferedImage. I get the BufferedImage by doing

(BufferedImage) fg;

fg is an image of my jPanel's graphics. 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.

My code for my attempt at utilizing the JFileChooser is as follows:

JFileChooser jfc = new JFileChooser();
int retVal = jfc.showSaveDialog(null);
    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.

I update my image when the JFrame has a mouse presses event:

fg = jPanel2.createImage(jPanel2.getWidth(), jPanel2.getHeight());

Best Solution

try to put this line of code I think that's what you need:

ImageIO.write(buffer, "png", fileDialog.getSelectedFile());

Hope that helps