MrEbbinghaus
MrEbbinghaus

Reputation: 1023

Saving a javafx.scene.canvas with transparent Pixels

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();
        }
    }
}

Upvotes: 11

Views: 5476

Answers (1)

Stuart Marks
Stuart Marks

Reputation: 132460

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);

Upvotes: 16

Related Questions