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

前端之家收集整理的这篇文章主要介绍了如何将JavaFX 2中的场景图形的内容输出到图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将 JavaFX 2中的场景图的内容输出到图像.实际上,我正在开发一款基本上设计卡片的应用程序.因此,用户只需单击各种选项即可自定义场景.最后,我想将场景内容导出到Image文件.我怎么做 ?

解决方法

在FX 2.2中出现了新的快照功能.你可以说
  1. WritableImage snapshot = scene.snapshot(null);

使用旧款FX,您可以使用AWT Robot.这不是一个很好的方法,因为它需要整个AWT堆栈才能启动.

  1. // getting screen coordinates of a node (or whole scene)
  2. Bounds b = node.getBoundsInParent();
  3. int x = (int)Math.round(primaryStage.getX() + scene.getX() + b.getMinX());
  4. int y = (int)Math.round(primaryStage.getY() + scene.getY() + b.getMinY());
  5. int w = (int)Math.round(b.getWidth());
  6. int h = (int)Math.round(b.getHeight());
  7. // using ATW robot to get image
  8. java.awt.Robot robot = new java.awt.Robot();
  9. java.awt.image.BufferedImage bi = robot.createScreenCapture(new java.awt.Rectangle(x,y,w,h));
  10. // convert BufferedImage to javafx.scene.image.Image
  11. java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
  12. // or you can write directly to file instead
  13. ImageIO.write(bi,"png",stream);
  14. Image image = new Image(new java.io.ByteArrayInputStream(stream.toByteArray()),h,true,true);

猜你在找的Java相关文章