简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM