当 Toolkit.getDefaultToolkit() 抛出 AWTError 时,如何在 Java 中读取图像?
我正在使用Java读取图像文件
java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath);
在某些系统上这不起作用,它会抛出一个AWTError抱怨sun/awt/motif/MToolkit。
还有什么方法可以从图像文件创建 java.awt.Image 对象?
I am reading image files in Java using
java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath);
On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit.
How else can you create a java.awt.Image object from an image file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ImageIO 中有几个静态方法允许从不同来源读取图像。 您的情况中最有趣的是:
我检查了代码内部。 它使用ImageReader抽象类,并且有三个实现者: JPEGReader。 PNGReader 和 GIFReader。 这些类和 BufferedImage 显然不使用任何本机方法,因此它应该始终有效。
您遇到的 AWTError 似乎是因为您在无头配置中运行 java,或者 Windows 工具包存在某种问题。 如果不看具体的错误就很难说。 此解决方案将允许您读取图像(可能),但根据您想要用它做什么,稍后当您尝试显示它时可能会抛出 AWTError 。
There is several static methods in ImageIO that allow to read images from different sources. The most interesting in your case are:
I checked inside in the code. It uses the ImageReader abstract class, and there is three implementors: JPEGReader. PNGReader and GIFReader. These classes and BufferedImage do not use any native methods apparently, so it should always work.
It seems that the AWTError you have is because you are running java in a headless configuration, or that the windows toolkit has some kind of problem. Without looking at the specific error is hard to say though. This solution will allow you to read the image (probably), but depending on what you want to do with it, the AWTError might be thrown later as you try to display it.
在某些系统上添加“-Djava.awt.headless=true”作为 java 参数可能会有所帮助。
On some systems adding "-Djava.awt.headless=true" as java parameter may help.
我使用 ImageIO 读取图像。
javadoc 还将提供更多信息。
I read images using ImageIO.
The javadoc will offer more info as well.