tags:

views:

893

answers:

3

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?

+4  A: 

I read images using ImageIO.

Image i = ImageIO.read(InputStream in);

The javadoc will offer more info as well.

jjnguy
yay! Glad I could help.
jjnguy
+1  A: 

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.

Mario Ortegón
A: 

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

Vilmantas Baranauskas