有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将JavaFX2中场景图的内容输出到图像

如何将JavaFX2中的Scene图的内容输出到Image。实际上,我正在开发一个应用程序,它基本上是设计卡片的。因此,用户只需单击各种选项即可自定义场景。最后,我想将场景内容导出到图像文件中。我该怎么做


共 (2) 个答案

  1. # 1 楼答案

    更新

    JavaFX2.2(jdk7u6)添加了节点snapshot to image特性,这将是完成此任务的首选方式


    在2.2之前,JavaFX目前没有将节点或场景转换为图像的公共功能。此http://javafx-jira.kenai.com/browse/RT-13751有一个开放的功能请求(任何人都可以注册以查看当前的功能请求状态)

    同时,作为一种解决方法,您可以使用Swing/AWT函数将JavaFX场景转换为图像,并将生成的图像写入文件:

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

    以上代码的意思是:JavaFXDev: Screen capture tool

    可通过以下方式确定温度:

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

    如果您遵循上述习惯用法,请小心线程——这样访问live JavaFX场景的代码只在JavaFX应用程序线程上运行,而AWT代码只在AWT线程上运行

  2. # 2 楼答案

    在FX2.2中,出现了新的快照功能。你可以说

    WritableImage snapshot = scene.snapshot(null);
    

    与旧的外汇,你可以使用AWT机器人。这不是很好的方法,因为它需要整个AWT堆栈才能启动

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