Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get height/width of image in Javascript (ideally without loading the image at all)

Tags:

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?

like image 370
Richard Avatar asked Nov 07 '09 09:11

Richard


People also ask

How do you get the image width and height using JS?

Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.

How do you find the width and height of an image in HTML?

Answer: Use the HTML5 naturalWidth and naturalHeight You can easily find the original or intrinsic width and heigh of an image using the HTML5 image naturalWidth and naturalHeight properties. These properties are supported in all major web browsers such as Chrome, Firefox, Safari, Opera, Internet Explorer 9 and above.

How can get image width and height in jquery?

width(); alert(imageWidth); var imageHeight = Imgsize. height();


1 Answers

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"; 
like image 105
luvieere Avatar answered Sep 27 '22 23:09

luvieere