简体   繁体   中英

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);
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.

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

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!");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM