How to output the content of a Scene
graph in JavaFX 2 to an Image
. Actually, I am working on an app, which basically designs cards. So, the user just clicks to the various options to customize the scene. Finally I would like to export the scene content to an Image file. How do I do that ?
In FX 2.2 new snapshot feature appeared for that matter. You can just say
WritableImage snapshot = scene.snapshot(null);
With older FX you can use AWT Robot. This is not very good approach as it requires whole AWT stack to start.
// getting screen coordinates of a node (or whole scene)
Bounds b = node.getBoundsInParent();
int x = (int)Math.round(primaryStage.getX() + scene.getX() + b.getMinX());
int y = (int)Math.round(primaryStage.getY() + scene.getY() + b.getMinY());
int w = (int)Math.round(b.getWidth());
int h = (int)Math.round(b.getHeight());
// using ATW robot to get image
java.awt.Robot robot = new java.awt.Robot();
java.awt.image.BufferedImage bi = robot.createScreenCapture(new java.awt.Rectangle(x, y, w, h));
// convert BufferedImage to javafx.scene.image.Image
java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
// or you can write directly to file instead
ImageIO.write(bi, "png", stream);
Image image = new Image(new java.io.ByteArrayInputStream(stream.toByteArray()), w, h, true, true);
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