How do I convert all of my graphics contents into a BufferedImage? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How do I convert all of my graphics contents into a BufferedImage?

I have in my Canvas class (extends JPanel) an override function: @Override public void paintComponent(Graphics g) { Graphics2D g2D = (Graphics2D)g; g2D.fillRect(0, 0, 400, 200); g2D.fillRect(0, 200, 400, 400); // BufferedImage img = g2D.image(); // how do I convert graphics to buffered image? g2D.dispose(); } Does anyone know if it's even possible?

20th Dec 2020, 8:45 AM
Frumkin
Frumkin - avatar
1 Answer
+ 2
Did you try something like this? private BufferedImage getPaintingOnBufferedImage() { BufferedImage result = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR); paintComponent(result.getGraphics()); return result; } PS: I usually draw in the paint method instead of paintComponent. paint can be used more consistently because some classes like JFrame have no paintComponent method. This may be mostly a matter of personal taste but I would refactor any complex drawing so it is done in a method that isn't tied to the component if it is being called to draw on an image. It is just slightly unusual to use paintComponent to draw on an image so using a method that doesn't override one of the component's methods to draw your image would be a little more normal.
23rd Dec 2020, 3:34 PM
Josh Greig
Josh Greig - avatar