JFrame to image without showing the JFrame

后端 未结 2 1777
天命终不由人
天命终不由人 2021-01-13 22:13

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:

相关标签:
2条回答
  • 2021-01-13 23:10

    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
    
    0 讨论(0)
  • 2021-01-13 23:11

    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();
    
    0 讨论(0)
提交回复
热议问题