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

时间:2016-01-17 08:02:21

标签: java jfreechart

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

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

3 个答案:

答案 0 :(得分:6)

解决方案是使用方法ChartUtilities.writeChartAsPNG

示例:

try {

    OutputStream out = new FileOutputStream(chartName);
    ChartUtilities.writeChartAsPNG(out,
            aJFreeChart,
            aChartPanel.getWidth(),
            aChartPanel.getHeight());

} catch (IOException ex) {
    logger.error(ex);
}

答案 1 :(得分:0)

另外,你可以这样做:

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 ); 
}

答案 2 :(得分:0)

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);

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