Image width/height

Hi,

When I want to get the width and height for an image, it often returns -1 even when the image is already loaded.
I fixed this by looping the getWidth and getHeight until they return something >-1, does anyone know if there’s a better solution for this?

public void imageBlah(Image im)
{
while (im.getWidth(null) < 1 && im.getHeight(null) < 1) { }

	int width = orig.getWidth(null);
	int height = orig.getHeight(null);
            .....

}

getHeight and Width return -1 when the size of the image is not yet known. This would probably be the case when the image is partially loaded (i.e. from a source on the web), but I don’t really know anything about this. Anyway, it could depend on the way you obtain these images, so maybe you should explain how you load them.

Either use MediaTracker or load the images through ImageIO.

So both those answers ae correct. To explain more clearly…

If you load images the old Java way, they load asynchronously,. So you need to use MediaTracker to wait til lthe image is fully loaded before you try to do anything with it. (This was to make behavior like you see i naweb-browser easy where the images are loaded in parallel to each other and any other loading that is going on.)

If you load with imageio, the load call will block until the image is fully loaded.

Sorry, I forgot to mention the image I pass to the mtehod imageBlah(Image im) is loaded by a method whihc uses the mediatracker:

public Image loadImage(String fielname)
{
Image img;
load the image over an url
mediaTracker.addImage(img, 0);
mediaTracker.waitForID(0);

return img;
}

Sadly ImageIO is no solution for me, as i have to stick to jdk1.1 specs :-\

If you’re using a swing panel or the like it has issues getting any sort of size if the screen is not already visible.

Also, try adding in

if (MediaTracker.imageStatus(image) == MediaTracker.COMPLETE)

before your checking. Not sure on the syntax of the first method name, I’ll look it up when I get back to my computer.