Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output the content of a Scenegraph in JavaFX 2 to an Image

Tags:

java

javafx-2

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 ?

like image 730
batman Avatar asked Feb 09 '12 17:02

batman


1 Answers

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);
like image 82
Sergey Grinev Avatar answered Sep 22 '22 06:09

Sergey Grinev