Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save current chart in ChartPanel as PNG programmatically?

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.

like image 437
zygimantus Avatar asked Jan 17 '16 08:01

zygimantus


2 Answers

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);
}
like image 189
zygimantus Avatar answered Oct 25 '22 09:10

zygimantus


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 ); 
}
like image 2
Damico Avatar answered Oct 25 '22 10:10

Damico