【问题标题】:JFrame to image without showing the JFrameJFrame 到图像而不显示 JFrame
【发布时间】:2012-09-19 00:06:06
【问题描述】:

我正在尝试将 JFrame 渲染到图像而不显示 JFrame 本身(类似于this 的问题)。我试过使用这段代码:

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 组件方面的经验非常有限,因此我们将不胜感激。

谢谢。

【问题讨论】:

  • @mKorbel:我发布的代码正是我想要做的。我曾尝试使用该类,但它也呈现黑色图像。
  • JComponents,然后 JFrames RootPane 可以返回其坐标或图形,对于已经可见的容器,在调用 pack() 之后,ContentPane 不是 Graphics(2d) 的正确容器,使用 JComponents / JPanel通过覆盖 get/setPreferredSize 或使用图像的调用实例(不确定有关其他方法的正确方法,图像,图形不是我的 Java 杯)

标签: java swing jframe bufferedimage


【解决方案1】:

这是一个可以解决问题的 sn-p:

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

【讨论】:

  • @DavidKroukamp 谢谢。我又看了一遍,createGraphics 返回一个 Graphics2D,所以不需要投射 ;-) 干杯。
  • 非常感谢这对我有用。我只需要将jFrame.getContentPane() 连同您的建议一起传递。还有一件事,使用ARGB 会产生略带粉红色的图像。我使用通常的RGB 来解决这个问题。
  • @npinti 这取决于您要实现的目标。如果您还想处理透明度,则需要 ARGB,否则,RGB 确实是您的朋友;)
  • @GuillaumePolet:确实如此。谢天谢地,它只是一张普通的图片,不需要透明度和额外的东西。
  • 不起作用(工作很奇怪)。除了在 bi 上绘图,它还可以在当前 GUI 上绘图。
【解决方案2】:

这种方法可能会奏效:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 2021-09-15
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多