如何将JavaFX 2中的场景图形的内容输出到图像

bat*_*man 7 java javafx-2

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

Ser*_*nev 9

在FX 2.2中出现了新的快照功能.你可以说

WritableImage snapshot = scene.snapshot(null);
Run Code Online (Sandbox Code Playgroud)

使用旧款FX,您可以使用AWT Robot.这不是一个很好的方法,因为它需要整个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);
Run Code Online (Sandbox Code Playgroud)