如何将 JFreeChart 的图形保存在 PNG 图像中?
Posted
技术标签:
【中文标题】如何将 JFreeChart 的图形保存在 PNG 图像中?【英文标题】:How to save the graph of JFreeChart in the PNG image? 【发布时间】:2018-11-04 05:59:30 【问题描述】:将收到的图形以图片的形式保存在计算机上的文件夹中时出现问题。在我看来,问题出在图片中的保存方法上,但我不知道如何解决问题。我在代码中标注了问题区域(saveImage
),希望对您有所帮助)
//create Graph
XYSeriesCollection seriesCollection1 = new XYSeriesCollection(series1);
chart1 = ChartFactory.createXYLineChart("Зависимость скорости полета от t",
"Время, с", "Скорость полета, км/ч", seriesCollection1, PlotOrientation.VERTICAL, false, true, false);
chartPanel1 = new ChartPanel(chart1);
chartPanel1.setPreferredSize(new Dimension(1300, 480));
panel.add(chartPanel1);
//saving method in picture
public void saveImage(File file)
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
print(img.getGraphics()); // I think problem here.
try
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
catch (IOException ex)
JOptionPane.showMessageDialog(null, "Ошибка сохранения", "", JOptionPane.ERROR_MESSAGE);
//listener
saveImage.addActionListener(new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
if (e.getSource() == saveImage)
JFileChooser fc = new JFileChooser();
int op = fc.showSaveDialog(OpenFIle.this);
if (op == JFileChooser.APPROVE_OPTION)
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4)
ext = filename.substring(len - 4, len);
if (ext.equals(".png"))
file = path + "\\" + filename;
else
file = path + "\\" + filename + ".png";
saveImage(new File(file));
);
【问题讨论】:
问题可能出在 print() 方法中。您也可以发布代码吗? 1) 将 catch (IOException ex) JOptionPane.showMessageDialog(..
更改为 有用 之类的东西,例如 catch (IOException ex) ex.printStacTrace(): JOptionPane.showMessageDialog(..
2) 为了尽快获得更好的帮助,请发布 minimal reproducible example 或 @987654322 @.
为什么不ChartUtils.saveChartAsPNG()
?
我不知道这种方法。谢谢,我试试
【参考方案1】:
问题就这样解决了
public void saveImage(File file)
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
chartPanel1.paint(g);
try
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
catch (IOException ex)
ex.printStackTrace();
【讨论】:
以上是关于如何将 JFreeChart 的图形保存在 PNG 图像中?的主要内容,如果未能解决你的问题,请参考以下文章