如何在javafx 2.1中将节点转换为图像? [英] How to convert node to image in javafx 2.1?

查看:223
本文介绍了如何在javafx 2.1中将节点转换为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java FX,我想将节点转换为图像。我找到了这个资源,但它并没有解决我的问题,因为我想将节点转换为图像,而不是整个场景。

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

如何将JavaFx 2.0中场景图的内容输出到图像

推荐答案

这是我的问题的解决方案。这个解决方案是Sergey和jewelsea的帮助。此解决方案位于javafx 2.2中。谢谢Sergey和jewelsea。

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

这篇关于如何在javafx 2.1中将节点转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆