Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a javafx.scene.canvas with transparent Pixels

Tags:

java

javafx-8

I'm trying to write a simple "Paint"-like JavaFX-Application. I draw on to a JavaFX.scene.canvas, this works quite well.

Now I want to save this canvas as a ".png" image. Works, but the transparent pixels where swapped with white ones.

How do I save transparent pixels, as transparent Pixels?

Here 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();
        }
    }
}
like image 309
MrEbbinghaus Avatar asked Jun 21 '14 16:06

MrEbbinghaus


1 Answers

The problem is that when you snapshot the canvas, the first argument to snapshot is null, which means that default SnapshotParameters are used. In particular, the entire destination image is first filled with the SnapshotParameter's fill value. Since the argument is null, the default fill value is null, which means that the fill value (see SnapshotParameters.setFill) is white.

To fix this, just create a SnapshotParameters object, set its fill to transparent, and use it in the call to snapshot:

    SnapshotParameters sp = new SnapshotParameters();
    sp.setFill(Color.TRANSPARENT);
    ...
    ImageIO.write(SwingFXUtils.fromFXImage(canvas.snapshot(sp, wi), null), "png", file);
like image 113
Stuart Marks Avatar answered Oct 18 '22 09:10

Stuart Marks