I don't understand the Image class! What am I doing wrong here?

image, java

Solution

`Toolkit.getDefaultToolkit().getImage()` might asynchronously load the image which is almost never what you want.

Use `ImageIO` and a `BufferedImage` instead which also has `getWidth()` and `getHeight()` without an `ImageObserver` parameter (although the other ones will work as well if you pass `null`):

BufferedImage image = ImageIO.read("/*image*/");
int width = image.getWidth();

Problem

quite a newbie here but here's a small test code that explains my issue. The value printed is -1. I just don't have the slightest clue on how to return the pixel width of my image, am I missing something very obvious here? This whole ImageObserver thingy makes no sense!!! ``` import java.awt.*; import javax.swing.*; import java.awt.event.*; class imagetest2 extends JPanel { Image i =Toolkit.getDefaultToolkit().getImage(/*image*/); public int test(){ int x = i.getWidth(null); return x; } } class imagetest { public static void main(String args[]){ imagetest2 tesst = new imagetest2(); System.out.print(tesst.test()); } } ```

Original source