Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

var pic = $("img")  // need to remove these in of case img-element has set width and height pic.removeAttr("width");  pic.removeAttr("height");  var pic_real_width = pic.width(); var pic_real_height = pic.height(); 

But in Webkit browsers like Safari and Google Chrome values are 0.

like image 935
Frank Bannister Avatar asked Nov 25 '08 19:11

Frank Bannister


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.

Can you change an images size using JavaScript?

Using JavaScript In plain JavaScript, you can directly modify the CSS width and height property of the image.

How do you measure intrinsic image size?

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.


1 Answers

Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:

var img = $("img")[0]; // Get my img elem var pic_real_width, pic_real_height; $("<img/>") // Make in memory copy of image to avoid css issues     .attr("src", $(img).attr("src"))     .load(function() {         pic_real_width = this.width;   // Note: $(this).width() will not         pic_real_height = this.height; // work for in memory images.     }); 

To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by FDisk.

You can also use the naturalHeight and naturalWidth HTML5 attributes.

like image 56
Xavi Avatar answered Sep 27 '22 20:09

Xavi