How to output Scenegraph content in JavaFX 2 to an image

How to display Scene plot contents in JavaFX 2 on Image . In fact, I am working on an application that mainly develops maps. Thus, the user simply clicks on various parameters to adjust the scene. Finally, I would like to export the contents of the scene to an image file. How to do it?

+6
source share
2 answers

FX 2.2 introduces a new snapshot function. You can just say

 WritableImage snapshot = scene.snapshot(null); 

With an older FX, you can use AWT Robot. This is not a good approach, as it requires the entire AWT stack to run.

  // 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); 
+9
source

Update

JavaFX 2.2 (jdk7u6) added a Node snapshot function to the image , which would be the preferred way to do this task.


Prior to 2.2, JavaFX does not currently have a public function for converting a Node or scene into an image. There is an open function request for this http://javafx-jira.kenai.com/browse/RT-13751 (anyone can register to view the current status of the function request).

As a workaround, you can use the Swing / AWT functions to convert the JavaFX scene to an image and write the resulting image to a file:

 BufferedImage img = new Robot().createScreenCapture( new java.awt.Rectangle( (int)sceneRect.getX(), (int)sceneRect.getY(), (int)sceneRect.getWidth()-1, (int)sceneRect.getHeight()-1)); File file = File.createTempFile("card", ".jpg"); ImageIO.write(img, "jpg", file); 

The above code is paraphrased from: JavaFXDev: Screen capture tool .

The scenario can be defined:

 Stage stage = (Stage) scene.getWindow(); stage.toFront(); Rectangle sceneRect = new Rectangle( stage.getX() + scene.getX(), stage.getY() + scene.getY(), scene.getWidth(), scene.getHeight()); 

If you follow the above idiom, be careful with stream processing — so that code accessing the live JavaFX script runs only in the JavaFX application thread, and AWT code only works in the AWT stream.

+4
source

Source: https://habr.com/ru/post/908059/


All Articles