How can I paint an image from BufferStrategy to Png file?

206 Views Asked by At

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.

2

There are 2 best solutions below

0
AudioBubble On

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
MadProgrammer On

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