gandalf
gandalf

Reputation: 27

How to create a Buffered Image of the content drawn on a Canvas?

I have a canvas on which I am adding primitive shapes like square, circles etc. Is it possible to get the content drawn on the canvas in form of a Buffered Image.

I actually aim to access single pixels from the canvas, and couldn't find a better way of doing this?

Upvotes: 1

Views: 1172

Answers (1)

CodeMed
CodeMed

Reputation: 9191

Try this approach:

1.) Create a bufferedimage the width and height of the canvas
2.) Create a graphics2D object from the new bufferedimage
3.) Use the paint(g2d) or paintall(g2d) method of your canvas object

So you have something like:

BufferedImage myBI = new BufferedImage(myCanvas.getWidth(), myCanvas.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = myBI.createGraphics();
myCanvas.paint(g);

Your canvas should now be painted into the bufferedimage.

The question of whether to draw from a canvas to a bufferedimage or to draw from a bufferedimage to a canvas has to do with speed and with image quality. Drawing to buffered image is faster than drawing to canvas, but that might not matter if you are just doing this for static images. But you may also notice a difference in image quality. I have printed jpanels to buffered image and then to jpg files, and have noticed reduced image quality.

Upvotes: 1

Related Questions