在不显示JFrame的情况下将JFrame转换为图片

7

我试图将JFrame渲染成图像,而不必显示JFrame本身(类似于问题所问的内容)。我已经尝试使用以下代码:

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;
}

然而,只有在设置JFramesetVisible(true)时才能有效。这将导致图像显示在屏幕上,这不是我想要的结果。我也尝试创建如下内容:
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);
    }
}

然而,这会显示黑色图像(就像上面的代码)。我相当确信我要实现的是可能的,问题在于我无法找到如何做到。我对自定义Swing组件的经验非常有限,因此任何信息都将不胜感激。

谢谢。


1
没有提供 SSCCE,这可能可以正常工作,但也可能会引起问题。点击此处查看相关编程内容。 - mKorbel
1
@mKorbel:我发布的代码就是我想要做的。我已经尝试使用那个类,但它也生成了黑色图像。 - npinti
1
JComponents,然后JFrames RootPane可以在已经可见的容器中调用pack()之后返回其坐标或Graphics。ContentPane不是Graphics(2d)的适当容器,请通过覆盖get/setPreferredSize使用JComponents/JPanel或使用Image的缩放实例(关于其他方法我不确定,Image,Graphics不是我的Java茶)。 - mKorbel
2个回答

12

这里是一个可以完成任务的代码片段:

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();

1
@DavidKroukamp 谢谢。我再看了一下,createGraphics返回一个Graphics2D,所以不需要强制转换;-) 干杯。 - Guillaume Polet
非常感谢,这对我很有帮助。我只需要将 jFrame.getContentPane() 与您建议的内容一起传递即可。还有一件事,使用 ARGB 会产生略带粉色的图像。我使用了通常的 RGB 来解决这个问题。 - npinti
@npinti 这取决于你想要实现什么。如果你想要处理透明度,你需要使用ARGB,否则RGB就足够了 ;) - Guillaume Polet
@GuillaumePolet:确实是这样。谢天谢地,它只是一张普通的图片,不需要透明度和额外的东西。 - npinti
无法工作(工作怪异)。除了在“bi”上绘制可以正常工作外,它还会在当前GUI的顶部进行绘制。 - Mark Jeronimus
@MarkJeronimus 它是有效的。你应该在SO上发布一个问题,附上完整的示例,这样我们就可以找出哪里出了问题。 - Guillaume Polet

4
这个方法可能会解决问题:
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;
}

然后你需要执行以下操作:

JFrame frame=...;
...
BufferedImage bImg=new ClassName().getImage(frame);
//bImg is now a screen shot of your frame

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接