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?


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01