Tuesday, July 31, 2007

get image size after image is fully loaded

If we need to get the size (width and height) of an image, in order to manipulate it, we first need to make sure that the image is fully loaded inside the web document. But at most time, we may not need to render the image, we just need the size. so here is a neat way to do this:

- using Image() object to load an image internally, without displaying the image in the doc, and then get the size.
function getWidthAndHeight() {
alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
return true;
}
function loadFailure() {
alert("'" + this.name + "' failed to load.");
return true;
}
var myImage = new Image();
myImage.name = "someimg.jpg";
myImage.onload = getWidthAndHeight;
myImage.onerror = loadFailure;
myImage.src = "someimg.jpg";

With this code, the image is 'silently' being loaded into the current document. The image is attached with an 'onload' event listener, that calls a function named getWidthAndHeight() Note that onload event for images are only triggered after the image is fully downloaded to the browsers cache. So then, they will be no problem for us to get the correct size.

Thanks to phpnovice for his solution taken from webdeveloper.com

No comments: