Search code examples
javafxml

Saving images using dialogs in java FXML (java 8)


So im trying to save a image (Image class from javafx.scene.image.Image) onto a file with a save file dialog (JFileChooser) so that it is user friendly.

What i want it to do: Save the image specified

What it does: Save dialog works (i think), and it doesn't save (write to file) anything.

Here is the code behind it:

    public void saveFile() { //menu item interface for save and save as
    JFrame parentFrame = new JFrame();
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Save");
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    //Setting the file extentions
    /*fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Image", ".png"));
    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG Image", ".jpg"));
    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("BMP Image", ".bmp"));*/

    int userSelection = fileChooser.showSaveDialog(parentFrame);

    if (userSelection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = fileChooser.getSelectedFile(); //selected file
        saveToFile(picFrame.getImage(), fileToSave); //save the file
        System.out.println("Save as file: " + fileToSave.getAbsolutePath()); //debug because it doesnt work
    }

    parentFrame.dispose();
}

and here is saveToFile

    public static void saveToFile(Image image, File file) {

    String extension = "";

    File outputFile = file;

    try {
        if (file != null && file.exists()) {
            String name = file.getName();
            extension = name.substring(name.lastIndexOf("."));
        }
    } catch (Exception e) {
        extension = "";
    }

    BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
    try {
        ImageIO.write(bImage, extension, outputFile);
        System.out.println("Saveing file");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Solution

  • After some digging arround and debuging i found the problem and the solution , so here it is. All the code.

        public void saveFile() { //menu item interface for save and save as
        Window mainStage = ap.getScene().getWindow(); //get ze window
    
        FileChooser fileChooser = new FileChooser(); //Filechooser the class that has the file chooser
        fileChooser.setTitle("Open Resource File"); //Title of prompt
        fileChooser.getExtensionFilters().addAll(                                       //add filter
                new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif", ".bmp"),  //Filters
                new ExtensionFilter("All Files", "*.*"));                               //Filters
        File selectedFile = fileChooser.showSaveDialog(mainStage); //get the file
        if (selectedFile != null) { //if something is selected then
            System.out.println(selectedFile.getAbsoluteFile()); //debug
            System.out.println(selectedFile.getAbsoluteFile().getParent()); //debug
            Image img = SwingFXUtils.toFXImage(bImg, null); //convert to Image
            saveToFile(img, selectedFile); //save the Image
        }
    
    }
    
    /**
     * A simple image save
     *
     * @param image The image you want to save
     * @param file The file where you want to save it
     */
    public static void saveToFile(Image image, File file) {
        File outputFile = file; //file
    
        BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); //Convert to bufferedimage
        try {
            ImageIO.write(bImage, getFileExtension(outputFile).toUpperCase(), outputFile.getAbsoluteFile()); //actualy save
            System.out.println("Saveing file ex: " + getFileExtension(outputFile).toUpperCase() + " to: " + outputFile.getAbsoluteFile() + " with name " + outputFile.getName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    private static String getFileExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf(".") + 1;
        if (lastIndexOf == -1) {
            return ""; // empty extension
        }
        return name.substring(lastIndexOf);
    }