0

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?

melar
  • 202
  • 2
  • 15
  • 3
    What is the extension of the file that you obtain when you call `chooser.getSelectedFile()`? – Hovercraft Full Of Eels Apr 13 '17 at 16:25
  • 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 Apr 13 '17 at 16:31
  • 1
    @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 Apr 13 '17 at 16:33
  • 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 only – melar Apr 13 '17 at 16:35
  • And now please answer what Hovercraft asked you: what is the _full_ filename of `chooser.getSelectedFile()`? – Tom Apr 13 '17 at 16:36
  • @tom, thanks for the input. i had to restructure my question, as i found out after solving the problem , that i was mixing things up a bit. – melar Apr 13 '17 at 17:00

1 Answers1

2

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) {
    ...
}
MVogeler
  • 36
  • 1
  • 4