Sunday, March 02, 2003

CodeBit; How Do I Load An Image and Determine Height and Width Using Java?

When loading an image over the net you frequently have to allow for long load times. The MediaTracker class is used to monitor a resource so that other things can happen (ie. threads) while the image is loading. However, sometimes you really need for the image to totally load because you need the height and width measurements before continuing. The following code fragment show how to wait for an image to finish loading. - from Bob Withers in comp.lang.java.api.

// url is a String containing the URL of the image to load.
MediaTracker tr;
Image        im = toolkit.getImage(url);

tr.addImage(im, 0);
tr.waitForID(0);

// at this point the image is finished
// loading and the height and width can
// be determined.
int w = im.getWidth(this);
int h = im.getHeight(this);
Post a Comment