How to convert node to image in javafx 2.1?

You can use new FX 2.2 snapshot feature:

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 older FX for some reason just change scene coordinates to your node coordinates using Node#getBoundsInParent calls in the code sample you linked.


This is solution of my problem. This solution is help of Sergey and jewelsea. This solution is in javafx 2.2. Thanks Sergey and jewelsea.

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);
    };
  }
 }