Search code examples
javaappletbufferedimagegraphics2d

Convert a Graphics2D to an Image or BufferedImage


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.


Solution

  • I do it that way, and works very well:


    BufferedImage awtImage = new BufferedImage(drawPanel.getWidth(), drawPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = awtImage.getGraphics();
    drawPanel.printAll(g);
    
    try
    {
    String caminhoImagem = System.getProperty("user.home") + "\\temps\\assinatura.jpg";
    FileOutputStream fos = new FileOutputStream(caminhoImagem);
    JPEGImageEncoderImpl j = new JPEGImageEncoderImpl(fos);
    j.encode(awtImage);
    fos.close();
    } catch(e) {..... }
    

    That's all :) Thanks everyone :)