tags:

views:

188

answers:

1

Hi

Sorry if this has already been answered, but I can't find it if so.

I want to find the height and width of an image file in Javascript. I don't actually need to show the image in the page, just the height and width.

At the moment I've got the following code, but it's returning height and width 0 (in Mozilla 5).

  var img = new Image();
  img.src = "./filename.jpg";
  var imgHeight = img.height;
  var imgWidth = img.width;
  alert("image height = "  + imgHeight + ", image width = " + imgWidth);

The file definitely exists, it's in the same directory as the HTML, and it doesn't have height and width 0 :)

What am I doing wrong?

+3  A: 

If the image is not loaded, it won't have its' height and width set. You have to wait until the image is fully loaded, then inspect its' size. Maybe something along these lines:

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 = "image.jpg";
myImage.onload = getWidthAndHeight;
myImage.onerror = loadFailure;
myImage.src = "image.jpg";
luvieere