Convert JPanel to image

前端 未结 4 2021
盖世英雄少女心
盖世英雄少女心 2020-12-03 17:12

Is there a way to convert a JPanel (that has not yet been displayed) to a BufferedImage?

thanks,

Jeff

4条回答
  •  一向
    一向 (楼主)
    2020-12-03 18:03

    From the BufferedImage you can create a graphics object, which you can use to call paint on the JPanel, something like:

    public BufferedImage createImage(JPanel panel) {
    
        int w = panel.getWidth();
        int h = panel.getHeight();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        panel.paint(g);
        g.dispose();
        return bi;
    }
    

    You may need to make sure you set the size of the panel first.

提交回复
热议问题