Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFrame to image without showing the JFrame

I am trying to render a JFrame to an image without ever displaying the JFrame itself (similar to what this question is asking). I have tried using this piece of code:

private static BufferedImage getScreenShot(Component component)
{
    BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
    // call the Component's paint method, using
    // the Graphics object of the image.
    component.paint(image.getGraphics());
    return image;
}

However, this only works when the JFrame's setVisible(true) is set. This will cause the image to be displayed on the screen which is not something I want. I have also tried to create something like so:

public class MyFrame extends JFrame
{
    private BufferedImage bi;

    public MyFrame(String name, BufferedImage bi)
    { 
         this.bi = bi;
         super(name);
    }

    @Override
    public void paint(Graphics g)
    {
         g.drawImage(this.bufferedImage, 0, 0, null);
    }
}

This however displays black images (like the code above). I am pretty sure that what I am after is possible, the problem is that I can't really find how. My experience with custom Swing components is pretty limited, so any information will be appreciated.

Thanks.

like image 323
npinti Avatar asked Sep 18 '12 12:09

npinti


2 Answers

Here is a snippet that should do the trick:

Component c; // the component you would like to print to a BufferedImage
JFrame frame = new JFrame();
frame.setBackground(Color.WHITE);
frame.setUndecorated(true);
frame.getContentPane().add(c);
frame.pack();
BufferedImage bi = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = bi.createGraphics();
c.print(graphics);
graphics.dispose();
frame.dispose();
like image 116
Guillaume Polet Avatar answered Oct 05 '22 13:10

Guillaume Polet


This method might do the trick:

public BufferedImage getImage(Component c) {
    BufferedImage bi = null;
    try {
        bi = new BufferedImage(c.getWidth(),c.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d =bi.createGraphics();
        c.print(g2d);
        g2d.dispose();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return bi;
}

you'd then do something like:

JFrame frame=...;
...
BufferedImage bImg=new ClassName().getImage(frame);
//bImg is now a screen shot of your frame
like image 43
David Kroukamp Avatar answered Oct 05 '22 13:10

David Kroukamp