How to save Image in a user selected format using FileChooser in javaFx?

2.3k views Asked by At

I am trying to save image in a user selected format from FileChooser SaveDialog. Here's my code:

java docs says the same thing for both get and set methods I dont get it.

    File f1 = new File("C:\\Users\\KIRAN\\Desktop\\Andromeda1.png");

    FileChooser stegoImageSaver = new FileChooser();
    stegoImageSaver.setTitle("Save Image File");
    stegoImageSaver.setInitialDirectory(new File("C:\\"));
    stegoImageSaver.getExtensionFilters().addAll(
        new FileChooser.ExtensionFilter("PNG Files", "*.png"),
        new FileChooser.ExtensionFilter("BMP Files", "*.bmp"),
        new FileChooser.ExtensionFilter("GIF Files", "*.gif"));
    File f1 = stegoImageSaver.showSaveDialog(null);

    ImageIO.write(img, "png", f1);

What i need is to get the extension from user from the "filechooser save dialog" and write the image with that extension.

I don't know how to use get&set extension methods in Filechooser in javaFx and couldn't find the practical implementation.

See my last line of code: I want to know how to change the "png" to whatever extension selected by the user from the "fileChooser save dialog".

Thanks in advance.

2

There are 2 answers

0
fabian On BEST ANSWER

The selected extension filter is only what the user selects from the combo box (or similar) in the dialog. This may or may not match the actual extension of the file. E.g. with windows you can select the png filter, but use the keyboard to input xyz.gif.

You should get the ending from the file returned from showSaveDialog:

File f1 = stegoImageSaver.showSaveDialog(null);
if (f1 != null) {
    String name = f1.getName();
    String extension = name.substring(1+name.lastIndexOf(".")).toLowerCase();
    ImageIO.write(img, extension, f1);
}
0
Eng-Mohamad Badr On

In a simple way, after you define ExtensionFilters you need, you can add them by this line

"fileChooser.getExtensionFilters().addAll(ex, exx);"

When click save the window will open and you can choice the extension that you need

    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter ex = new FileChooser.ExtensionFilter("jpg_Image", "*.jpg"); //Add as you need
    FileChooser.ExtensionFilter exx = new FileChooser.ExtensionFilter("GIF", "*.gif"); //Add as you need
    fileChooser.getExtensionFilters().addAll(ex, exx);
  File file = fileChooser.showSaveDialog(null);
    if (file != null) {
        ImageIO.write (SwingFXUtils.fromFXImage( myImgView.getImage(),null), "png", file);
    }

you can put any default extension in the last line but you still can choose from the extensions that you defined.