Convert a Graphics2D to an Image or BufferedImage

Viewed 62174

I have a little problem here.

I have an applet, where user can "draw" inside it. To do that, I use the java.awt.Graphics2D. But, how can I do to save the user draw image as a JPEG image, or at least, convert it to a BufferedImage or something? I don't know how to do that.

Thanks.

5 Answers

If you'd like to draw JComponent's image onto BufferedImage (JApplet extends JComponent):

JComponent whatToDraw = ...;
BufferedImage img = new BufferedImage(whatToDraw.getWidth(), 
        whatToDraw.getHeight(), BufferedImage.TYPE_INT_RGB);
whatToDraw.printAll(img.getGraphics());

And to write its data to JPEG file:

ImageIO.write(img, "jpg", new File("something.jpg"));
Related