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

StackOverflow https://stackoverflow.com/questions/119857

  •  02-07-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

I read images using ImageIO.

Image i = ImageIO.read(InputStream in);

The javadoc will offer more info as well.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top