如何从 java 中的组件获取 BufferedImage?

2022-01-21 00:00:00 components java bufferedimage

我知道如何从 JComponent 中获取 BufferedImage,但是如何从 java 中的 Component 中获取 BufferedImage 呢?这里的重点是组件"类型的对象,而不是 JComponent.

I know how to get a BufferedImage from JComponent, but how to get a BufferedImage from a Component in java ? The emphasis here is an object of the "Component" type rather than JComponent.

我尝试了以下方法,但它返回一个全黑的图像,这是什么问题?

I tried the following method, but it return an all black image, what's wrong with it ?

  public static BufferedImage Get_Component_Image(Component myComponent,Rectangle region) throws IOException
  {
    BufferedImage img = new BufferedImage(myComponent.getWidth(), myComponent.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = img.getGraphics();
    myComponent.paint(g);
    g.dispose();
    return img;
  }

推荐答案

Component 有一个方法 paint(Graphics).该方法将在传递的图形上绘制自己.这就是我们要用来创建 BufferedImage 的东西,因为 BufferedImage 有方便的方法 getGraphics().这将返回一个 Graphics 对象,您可以使用该对象在 BufferedImage 上进行绘制.

Component has a method paint(Graphics). That method will paint itself on the passed graphics. This is what we are going to use to create the BufferedImage, because BufferedImage has the handy method getGraphics(). That returns a Graphics-object which you can use to draw on the BufferedImage.

更新:但我们必须预先配置绘图方法的图形.这就是我在 java.sun.com:

UPDATE: But we have to pre-configure the graphics for the paint method. That's what I found about the AWT Component rendering at java.sun.com:

当 AWT 调用此方法时,图形对象参数是预先配置了适当的绘制这个特定的状态组件:

When AWT invokes this method, the Graphics object parameter is pre-configured with the appropriate state for drawing on this particular component:

  • Graphics 对象的颜色设置为组件的前景属性.
  • Graphics 对象的字体设置为组件的字体属性.
  • Graphics 对象的平移设置为坐标 (0,0) 表示组件的左上角.
  • Graphics 对象的剪切矩形设置为需要重绘的组件区域.

所以,这是我们的结果方法:

So, this is our resulting method:

public static BufferedImage componentToImage(Component component, Rectangle region) throws IOException
{
    BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics g = img.getGraphics();
    g.setColor(component.getForeground());
    g.setFont(component.getFont());
    component.paintAll(g);
    if (region == null)
    {
        region = new Rectangle(0, 0, img.getWidth(), img.getHeight());
    }
    return img.getSubimage(region.x, region.y, region.width, region.height);
}

相关文章