How to create/save the image of a JavaFX pie chart without actually showing the window?

JavaFXObject Oriented ProgrammingProgramming

The javafx.scene.chart package of JavaFX provides classes to create various charts namely: line chart, area chart, bar chart, pie chart, bubble chart, scatter chart, etc..

To create either of these charts you need to −

  • Instantiate the respective class.

  • Set the required properties.

  • Create a layout/group object to hold the chart.

  • Add the layout/group object to the scene.

  • Show the scene by invoking the show() method.

This will show the desired chart on the JavaFX window.

Saving the image without showing the window

The snapshot() method of the Scene class takes a snapshot of the current scene and returns it as a WritableImage Object.

Using the FromFXImage() method of the SwingFXUtils class you can get the BufferedImage from the obtained WritableImage and write it in a required file locally, as −

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

Example

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

Output

If you observe the output path, you can find the saved image as shown below −

raja
Published on 19-May-2020 15:46:43
Advertisements