2012-02-09 81 views
6

如何輸出Scene圖表的JavaFX中2中的內容到Image。其實,我正在研究一款基本上設計卡片的應用程序。因此,用戶只需點擊各種選項即可自定義場景。最後,我想將場景內容導出爲圖像文件。我怎麼做 ?如何輸出JavaFX中2一個場景圖的內容到圖像

回答

9

在FX 2.2新快照功能出現了這一問題。你只能說

WritableImage snapshot = scene.snapshot(null); 

年紀較大的FX您可以使用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); 
+0

我已經更新的答案,由於新的FX 2.2快照功能 – 2012-09-08 13:23:44

4

更新

JavaFX的2.2(jdk7u6)加入一個節點snapshot to image特徵這將是完成此任務的首選方式。


2.2之前,JavaFX的目前沒有一個公共功能節點或場景轉換爲圖像。有這個http://javafx-jira.kenai.com/browse/RT-13751(人可以註冊以查看當前的特徵請求狀態)的開放功能請求。

由於在此期間解決方法,你可以使用Swing/AWT功能,JavaFX的場景轉換爲圖像並將得到的圖像寫入文件:JavaFXDev: Screen capture tool

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

上面的代碼是從轉述。

的sceneRect可由下式確定:

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

如果你按照上面的成語,小心線程的 - 這樣的代碼訪問實時JavaFX的場景只能運行在JavaFX應用程序線程和AWT代碼只在AWT線程上運行。

+1

看起來像謝爾蓋已經發布瞭解決方案,同時我在寫我的答案 - 好像這兩個解決方案很相似;-)我會離開我重複的答案它包含一些有用的鏈接。 – jewelsea 2012-02-09 19:19:38

相關問題