8

I have created a JFreeChart in a ChartPanel and I want to save it programmatically. The functionality should exist as it is possible to do this manually (right click menu and PNG option from there).

I found the method chartPanel.createImage(??, ??), but I don't know what width and height I need to set.

TT.
  • 15,774
  • 6
  • 47
  • 88
zygimantus
  • 3,649
  • 4
  • 39
  • 54

3 Answers3

10

The solution was to use a method ChartUtilities.writeChartAsPNG

Example:

try {

    OutputStream out = new FileOutputStream(chartName);
    ChartUtilities.writeChartAsPNG(out,
            aJFreeChart,
            aChartPanel.getWidth(),
            aChartPanel.getHeight());

} catch (IOException ex) {
    logger.error(ex);
}
zygimantus
  • 3,649
  • 4
  • 39
  • 54
2

Also, you can do this:

public static void exportAsPNG throws IOException {
    JFreeChart chart = createChart(createDataset());


    BufferedImage image = new BufferedImage(600, 400, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();

    g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
    Rectangle r = new Rectangle(0, 0, 600, 400);
    chart.draw(g2, r);
    File f = new File("/tmp/PNGTimeSeriesChartDemo1.png");



    BufferedImage chartImage = chart.createBufferedImage( 600, 400, null); 
    ImageIO.write( chartImage, "png", f ); 
}
Damico
  • 1,107
  • 10
  • 5
  • 1
    Could you explain what is the advantage of your answer over the accepted, embedded one? – Line Feb 18 '19 at 16:03
2

Prior to version 1.5 use ChartUtilities class

ChartUtilities.saveChartAsPNG(<File>, chart, width, height);
ChartUtilities.writeChartAsPNG(<OutputStream>, chart, width, height);

With version 1.5 JFreeChart renamed ChartUtilities class to ChartUtils. It offers the same functionality.

ChartUtils.saveChartAsPNG(<File>, chart, width, height);
ChartUtils.writeChartAsPNG(<OutputStream>, chart, width, height);

Please note that there are more variants of those methods.