我正在尝试将已绘制的 bufferedImage 保存为新文件。我打开文件,使用 graphics2d 在其上绘制(然后在 JFrame 中显示图像以确保其正常工作),然后将其保存到新文件中。
问题是:保存的文件只是原始图像。它不包含我在上面绘制的任何新图形。
这是我的代码的简化版本:
public driver() throws IOException {
try {
image = ImageIO.read(new File("src/mc_map.png"));
} catch (IOException e) { e.printStackTrace(); }
this.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
image = process(image);
}
稍后在另一种方法中:
g.draw(new Line2D.Double(road.start.x, road.start.y, road.end.x, road.end.y));
...
br.close();
image.createGraphics();
File map = new File("map.png");
ImageIO.write(image, "png", map);
相关方法:
private BufferedImage process(BufferedImage old) throws IOException {
int w = old.getWidth();
int h = old.getHeight();
BufferedImage img = new BufferedImage(
w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(old, 0, 0, null);
g2d.setPaint(Color.BLUE);
g2d.drawLine(407, 355, 371, 349);
readAndDraw(g2d);
g2d.dispose();
return img;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
private static void create() throws IOException {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new driver());
f.pack();
f.setVisible(true);
}