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();
}
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With