简体   繁体   中英

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

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.

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

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