0
votes

Here is the snippet where i save the image with a .png extension:

 WritableImage img = rectCanvas.snapshot(new SnapshotParameters(), null);
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        int result = chooser.showSaveDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
        File fileToSave = chooser.getSelectedFile();
                ImageIO.write(SwingFXUtils.fromFXImage(img, null), "png", fileToSave);
            } catch (IOException ex) {
                Logger.getLogger(GuiClass.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

I want .png to be my default file extension. However when i want to save an image to file and open the save dialog i have to enter the file name in the following format: filename.png. How can i get rid of the .png part and make it default?

1
What is the extension of the file that you obtain when you call chooser.getSelectedFile()?Hovercraft Full Of Eels
When i look at the properties of the saved file i see .file .does that answer the question or did i get your question wrong?melar
@melar You open a file chooser. What do you do with that file chooser? Do you enter a new file name? If so, what do you enter? Do you select an existing file? If so, what is its name and extension?JB Nizet
sorry, now i got it. yes i choose the directory and enter a file name, but not the extension. i'm specifying the file format in the write method onlymelar
And now please answer what Hovercraft asked you: what is the full filename of chooser.getSelectedFile()?Tom

1 Answers

2
votes

What are you setting as the value of "fileToSave"? If that isn't .png, it shouldn't be a png extension.

See the following from oracle's documentation:

try {
    // retrieve image
    BufferedImage bi = getMyImage();
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    ...
}