Saving javafx.scene.canvas with transparent pixels

I am trying to write a simple "Paint" -like JavaFX application. I will describe in JavaFX.scene.canvas, this works pretty well.

Now I want to save this canvas as a ".png" image. It works, but transparent pixels, where they are replaced by white ones.

How to save transparent pixels as transparent pixels?

This is how I save the canvas:

private void saveFile(){
    FileChooser fc = new FileChooser();
    fc.setInitialDirectory(new File("res/maps"));
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PNG","*.png"));
    fc.setTitle("Save Map");
    File file = fc.showSaveDialog(primaryStage);
    if(file != null){
        WritableImage wi = new WritableImage((int)WIDTH,(int)HEIGHT);
        try {                    ImageIO.write(SwingFXUtils.fromFXImage(canvas.snapshot(null,wi),null),"png",file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
+4
source share
1 answer

, snapshot null, , SnapshotParameters . , SnapshotParameter. null, null, , (. SnapshotParameters.setFill) .

, SnapshotParameters, snapshot:

    SnapshotParameters sp = new SnapshotParameters();
    sp.setFill(Color.TRANSPARENT);
    ...
    ImageIO.write(SwingFXUtils.fromFXImage(canvas.snapshot(sp, wi), null), "png", file);
+9

Source: https://habr.com/ru/post/1545492/


All Articles