Image getWidth and getHeight returning -1 inapprop

2019-07-03 03:53发布

Why does this:

URL url = MinecraftPlatformGame.class.getResource("images/diamondPick.png");
image = Toolkit.getDefaultToolkit().getImage(url); 
int width = image.getWidth(null);
int height = image.getHeight(null);
System.out.println(width);
System.out.println(height);

Return -1 for both the width and the height

Edit: My question before I figured out the answer was actually how I was supposed to fix it. I fixed it by doing the following:

URL url = MinecraftPlatformGame.class.getResource("images/diamondPick.png");
image = Toolkit.getDefaultToolkit().getImage(url); 
MediaTracker mTracker = new MediaTracker(this);
  mTracker.addImage(image,1);
        try {
            mTracker.waitForID(1);
        } catch (InterruptedException ex) {
            Logger.getLogger(MinecraftPlatformGame.class.getName()).log(Level.SEVERE, null, ex);
        }
int width = image.getWidth(null);
int height = image.getHeight(null);
System.out.println(width);
System.out.println(height);

url = MinecraftPlatformGame.class.getResource("images/gui.png");
image1 = Toolkit.getDefaultToolkit().getImage(url);
  mTracker.addImage(image1,2);
        try {
            mTracker.waitForID(2);
        } catch (InterruptedException ex) {
            Logger.getLogger(MinecraftPlatformGame.class.getName()).log(Level.SEVERE, null, ex);
        }
        width = image1.getWidth(null);
height = image1.getHeight(null);
System.out.println(width);
System.out.println(height);

Problem I have now is this doesn't seem very efficient nor does it seem like I should need so much code just for two images to be imported and given sizes. Is there a better more efficient and easier way to do this?

标签: java
1条回答
叛逆
2楼-- · 2019-07-03 04:42

Per the Javadoc:

If the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later.

In response to your edit, and following Russell's comment, use ImageIO.read() instead to get a fully-loaded image.

查看更多
登录 后发表回答