[英]How to save current chart in ChartPanel as PNG programmatically?
我在ChartPanel
中创建了一个JFreeChart
,我想以编程方式保存它。 该功能应该存在,因为可以手动执行此操作(右键单击菜单和PNG
选项)。
我找到了方法chartPanel.createImage(??, ??)
,但我不知道我需要设置什么width
和height
。
解决方案是使用ChartUtilities.writeChartAsPNG
方法
例子:
try {
OutputStream out = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(out,
aJFreeChart,
aChartPanel.getWidth(),
aChartPanel.getHeight());
} catch (IOException ex) {
logger.error(ex);
}
另外,您可以这样做:
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 );
}
在 1.5 版之前使用ChartUtilities
类
ChartUtilities.saveChartAsPNG(<File>, chart, width, height);
ChartUtilities.writeChartAsPNG(<OutputStream>, chart, width, height);
在 1.5 版中,JFreeChart 将ChartUtilities
类重命名为ChartUtils
。 它提供相同的功能。
ChartUtils.saveChartAsPNG(<File>, chart, width, height);
ChartUtils.writeChartAsPNG(<OutputStream>, chart, width, height);
请注意,这些方法有更多变体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.