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 );
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.