Reputation: 497
I am attempting to save a bufferedImage that I have drawn on as a new file. I open the file, use graphics2d to draw on it (then display the image in a JFrame to make sure its working, which it does) and then saving it to a new file.
The problem is: The file that gets saved is only the original image. It does not contain any of the new graphics that I have drawn on it.
Here is a much simplified version of my code:
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);
}
later in another method:
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);
relevant methods:
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);
}
Upvotes: 2
Views: 3093
Reputation: 324078
then display the image in a JFrame to make sure its working
Use Screen Image to get a BufferedImage of any component and save the image to a file.
Upvotes: 2
Reputation: 41
I faced a very similar problem to you very recently so here is my solution :).
frame simply refers to your JFrame that you are drawing on, width and height refer to the size of the image your are saving.
try {
BufferedImage saving = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = saving.createGraphics();
frame.paint(graphics);
g.dispose(graphics);
File map = new File("map.png");
ImageIO.write(saving, "png", map);
} catch(IOException exc) {
System.out.println("problem saving");
}
EDIT: If your JFrame contains anything other than the image you wish to save I would recommend adding a JPanel to your JFrame and draw to that instead. You would draw in an almost identical manner to what you are doing now but when saving you would replace frame in your code with the name of your JPanel.
Upvotes: 2