Javascript's way to know the image size

作者:   發佈於:  

In reply to my own article: jquery way to limit image size.

It's actually very easy to known the size of an image using Javascript. Here's the code:

var i = new Image();
i.src = "http://www.google.com.tw/intl/en_com/images/logo_plain.png";

alert(i.width + " x " + i.height);

The Image object has be used to pre-load big images. If the image is known to be pretty big and it takes sometimes to load, you might want to examine its size only after it's loaded:

var i = new Image();
i.onload = function() {
    alert(i.width + " x " + i.height);
};
i.src = "http://www.google.com.tw/intl/en_com/images/logo_plain.png";

Notice that you'll have to set the onload function before you set src. Otherwise, when the browser has cached the image locally, the "load" event might be triggered instantly, even before the onload handler is set.

One nice thing it's that this can work with images from different domains. Just like you can put images from different domains into your page with img tags.