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.
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);
}
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With