How to convert node to image in javafx 2.1?

I am using Java FX and I would like to convert node to image. I found this resource, but it does not solve my problem, since I want to convert the node to an image, not an entire scene.

How to output the contents of a scene graph in JavaFx 2.0 to an image

+6
source share
2 answers

This is the solution to my problem. This decision helps Sergey and the jeweler. This solution is in javafx 2.2. Thanks to Sergey and the jeweler.

public class TrySnapshot extends Application { javafx.embed.swing.SwingFXUtils fXUtils; BufferedImage bufferedImage = new BufferedImage(550, 400, BufferedImage.TYPE_INT_ARGB); File file = new File("C:/Users/PC1/Desktop/Sample Images/test.jpg"); VBox vbox = null; @Override public void start(Stage primaryStage) { vbox = new VBox(); Button btn = new Button(); Image i = new Image("file:C:\\Koala.jpg"); ImageView imageView = new ImageView(); imageView.setImage(i); vbox.getChildren().add(imageView); vbox.setSpacing(10); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // here we make image from vbox and add it to scene, can be repeated :) WritableImage snapshot = vbox.snapshot(new SnapshotParameters(), null); vbox.getChildren().add(new ImageView(snapshot)); saveImage(snapshot); System.out.println(vbox.getChildren().size()); } }); Scene scene = new Scene(new Group(btn), 500, 400); primaryStage.setScene(scene); primaryStage.show(); } private void saveImage(WritableImage snapshot) { BufferedImage image; image = javafx.embed.swing.SwingFXUtils.fromFXImage(snapshot, bufferedImage); try { Graphics2D gd = (Graphics2D) image.getGraphics(); gd.translate(vbox.getWidth(), vbox.getHeight()); ImageIO.write(image, "png", file); } catch (IOException ex) { Logger.getLogger(TrySnapshot.class.getName()).log(Level.SEVERE, null, ex); }; } } 
+5
source

You can use the new FX 2.2 snapshot function:

 public class TrySnapshot extends Application { @Override public void start(Stage primaryStage) { final VBox vbox = new VBox(2); final Button btn = new Button(); vbox.getChildren().add(btn); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // here we make image from vbox and add it to scene, can be repeated :) WritableImage snapshot = vbox.snapshot(new SnapshotParameters(), null); vbox.getChildren().add(new ImageView(snapshot)); System.out.println(vbox.getChildren().size()); } }); Scene scene = new Scene(new Group(vbox), 300, 250); primaryStage.setScene(scene); primaryStage.show(); } 

If you must use an older FX, for some reason, just change the scene coordinates to your node coordinates using the Node#getBoundsInParent calls in the code sample that you linked.

+11
source

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


All Articles