如何从Java中的组件获取BufferedImage? [英] How to get a BufferedImage from a Component in java?
问题描述
我知道如何从JComponent获取BufferedImage,但是如何从Java中的Component获取BufferedImage呢?
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;
}
推荐答案
组件
具有方法 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
.
更新:但是我们必须为paint方法预先配置图形。这就是我在 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调用此方法时,
Graphics对象参数为
并预先配置了适当的$用于绘制此特定
组件的b $ b状态:
When AWT invokes this method, the Graphics object parameter is pre-configured with the appropriate state for drawing on this particular component:
- Graphics对象的颜色设置为组件的前台属性。 / li>
- 图形对象的字体设置为组件的font属性。
- 图形对象的转换设置为使得坐标(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);
}
这篇关于如何从Java中的组件获取BufferedImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!