Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FileChooser to save a writableimage image

I have a writableimage and I want to save by using a FileChooser. How would I do this, as it doesn't work with this code:

public void handle(ActionEvent event) {
          FileChooser fileChooser = new FileChooser();

          //Set extension filter
          FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
          fileChooser.getExtensionFilters().add(extFilter);

          //Show save file dialog
          File file = fileChooser.showSaveDialog(primaryStage);

          if(file != null){
              SaveFile(writableImage, file);
          }
      }

Here is the code for the SaveFile() Class:

private void SaveFile(writableimage content, File file){
    try {
        FileWriter fileWriter = null;

        fileWriter = new FileWriter(file);
        fileWriter.write(content);
        fileWriter.close();
    } catch (IOException ex) {
    }

}
like image 492
Will A Avatar asked Sep 18 '25 19:09

Will A


1 Answers

Instead of using a file writer you would need an AWT buffered image reader, try this

private void SaveFile(Image content, File file){
    try {
        BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
        ImageIO.write(bufferedImage, "png", file);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

I also found this online http://java-buddy.blogspot.com/2014/12/javafx-filechooser-open-and-save-image.html

Edit: You should also print your exception because when it breaks and you don't know why it will tell what line broke it

like image 194
Matt Avatar answered Sep 21 '25 14:09

Matt