Chris Carruthers
Chris Carruthers

Reputation: 3975

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

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?

Upvotes: 6

Views: 7218

Answers (3)

Vilmantas Baranauskas
Vilmantas Baranauskas

Reputation: 6726

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

Upvotes: 0

Mario Ortegón
Mario Ortegón

Reputation: 18900

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.

Upvotes: 2

jjnguy
jjnguy

Reputation: 138884

I read images using ImageIO.

Image i = ImageIO.read(InputStream in);

The javadoc will offer more info as well.

Upvotes: 6

Related Questions