How do you read an image in Java when Toolkit.getDefaultToolkit() throws an AWTError?

▼魔方 西西 提交于 2019-12-07 03:22:38

问题


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?


回答1:


I read images using ImageIO.

Image i = ImageIO.read(InputStream in);

The javadoc will offer more info as well.




回答2:


There is several static methods in ImageIO that allow to read images from different sources. The most interesting in your case are:

BufferedImage read(ImageInputStream stream) 
BufferedImage read(File input)
BufferedImage read(InputStream input)

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.




回答3:


On some systems adding "-Djava.awt.headless=true" as java parameter may help.



来源:https://stackoverflow.com/questions/119857/how-do-you-read-an-image-in-java-when-toolkit-getdefaulttoolkit-throws-an-awte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!