How to get a BufferedImage from a Component in java?(如何从 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);
}
这篇关于如何从 java 中的组件获取 BufferedImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 java 中的组件获取 BufferedImage?
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01