如何以编程方式将 ChartPanel 中的当前图表保存为 PNG?

How to save current chart in ChartPanel as PNG programmatically?

我在 ChartPanel 中创建了一个 JFreeChart,我想以编程方式保存它。该功能应该存在,因为可以手动执行此操作(右键单击菜单和那里的 PNG 选项)。

找到方法chartPanel.createImage(??, ??),但不知道widthheight需要设置什么

解决方法是使用一种方法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 class

ChartUtilities.saveChartAsPNG(<File>, chart, width, height);
ChartUtilities.writeChartAsPNG(<OutputStream>, chart, width, height);

JFreeChart 1.5 版将 ChartUtilities class 重命名为 ChartUtils。它提供相同的功能。

ChartUtils.saveChartAsPNG(<File>, chart, width, height);
ChartUtils.writeChartAsPNG(<OutputStream>, chart, width, height);

请注意,这些方法还有更多变体。