如何在不實際顯示視窗的情況下建立/儲存 JavaFX 餅圖的影像?


JavaFX 的 **javafx.scene.chart** 包提供了建立各種圖表(例如:折線圖、面積圖、條形圖、餅圖、氣泡圖、散點圖等)的類。

要建立這些圖表中的任何一個,您需要:

  • 例項化相應的類。

  • 設定所需的屬性。

  • 建立一個佈局/組物件來容納圖表。

  • 將佈局/組物件新增到場景。

  • 透過呼叫 **show()** 方法顯示場景。

這將在 JavaFX 視窗上顯示所需的圖表。

在不顯示視窗的情況下儲存影像

**Scene** 類的 **snapshot()** 方法會拍攝當前場景的快照,並將其作為 **WritableImage** 物件返回。

使用 **SwingFXUtils** 類的 **FromFXImage()** 方法,您可以從獲得的 **WritableImage** 獲取 **BufferedImage**,並將其寫入本地所需的 **檔案**,如下所示:

ImageIO.write(SwingFXUtils.fromFXImage(image, null), "PNG", file);

示例

import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart;
import javafx.scene.image.WritableImage;
public class ChartsExample extends Application {
   public void start(Stage stage) throws IOException {
      //Preparing ObservbleList object
      ObservableList<PieChart.Data>pieChartData =
      FXCollections.observableArrayList(
      new PieChart.Data("Iphone 5S", 13),
      new PieChart.Data("Samsung Grand", 25),
      new PieChart.Data("MOTO G", 10),
      new PieChart.Data("Nokia Lumia", 22));
      //Creating a Pie chart
      PieChart pieChart = new PieChart(pieChartData);
      pieChart.setTitle("Mobile Sales");
      pieChart.setClockwise(true);
      pieChart.setLabelLineLength(50);
      pieChart.setLabelsVisible(true);
      pieChart.setStartAngle(180);
      //Creating a Group object
      Scene scene = new Scene(new Group(), 595, 400);
      stage.setTitle("Charts Example");
      ((Group) scene.getRoot()).getChildren().add(pieChart);
      //Saving the scene as image
      WritableImage image = scene.snapshot(null);
      File file = new File("D:\JavaFX\tempPieChart.png");
      ImageIO.write(SwingFXUtils.fromFXImage(image, null), "PNG", file);
      System.out.println("Image Saved");
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

如果您觀察輸出路徑,您可以找到如下所示的儲存影像:

更新於:2020年5月19日

1K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.