I am making a method that returns the width and height of an image.
It’s an ordinary 32×32 icon. Here is what I did so far:
Image icon;
String filename = "G:\\icon.jpg";
int iconWidth = 0;
int iconHeight = 0;
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
The code outputs
-1
32
32 is the correct width of the image. But why does it first return -1? The code is exactly the same. Removing the “JFrame” line makes it return two -1s. Could the JFrame be affecting the default toolkit?
I also tried this code:
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
It also returns -1. I simply can’t understand why I have to call it twice to get a correct result.
From the docs for
getWidth:So perhaps the image is still being loaded asynchronously. Try using an ImageObserver so you can be notified when the information becomes available.