0

I've created a Java program that generates snowflakes and I'd like to save the image created as a .png file once the program finishes drawing.

I've searched on Internet, but I've found only programs using BufferedImage, while I use a BufferStrategy, so I don't know exactly where to start.

The draw method in my program uses a BufferStrategy to create the Graphics component. For example, to draw a simple line the method is:

bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
    display.getCanvas().createBufferStrategy(3);
    return;
}

g = bs.getDrawGraphics();
g.clearRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawLine(0, 0, 50, 50);

What I would like is to get an exact copy of what has been drawn on the screen by the program to be saved as a .png image. Hope you can help me.

  • All you need to do is pass the Graphics object (g) that you created into paint/paintComponent/paintAll from the top level down – ControlAltDel Jan 29 '19 at 15:29
  • If you look here at how I did this back in the day, all you need to do is send your Graphics object to paint: https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/print/StandardPrint.java – ControlAltDel Jan 29 '19 at 15:33
  • Instead of painting to the Graphics context of the BufferedStrategy, paint to Graphics context of the image – MadProgrammer Jan 29 '19 at 18:41

2 Answers2

0

Why not take a screenshot and then past it onto MS paint or some other(and better) image editing software like Photoshop or fire alpaca? That should solve your problem.

0

The common denominator between BufferedStrategy and BufferedImage is Graphics, so you want to write a paint routine so that you can simply pass a reference of Graphics to it

public void render(Graphics g) {
    g.clearRect(0, 0, width, height);
    g.setColor(Color.BLACK);
    g.drawLine(0, 0, 50, 50);
}

Then you can pass what ever context you want.

BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_RGB);
Graphics2D g2d = img.createGraphics();
render(g2d);
g2d.dispose();

Then you can use ImageIO.write to write the image to disk. See Writing/Saving an Image for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366