How to save current chart in ChartPanel as PNG programmatically?
Asked Answered
F

3

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.

Flower answered 17/1, 2016 at 8:2 Comment(0)
F
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);
}
Flower answered 17/1, 2016 at 8:13 Comment(2)
Why not one of the ChartUtilities.saveChartAsPNG() variations?Keynote
At the version 1.5.0 the classe ChartUtilities changed to org.jfree.chart.ChartUtils;Lexeme
A
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 ); 
}
Aurilia answered 26/1, 2018 at 14:39 Comment(1)
Could you explain what is the advantage of your answer over the accepted, embedded one?Winnie
A
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.

Amadus answered 6/11, 2020 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.