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

get image width and height onload

Webkit browsers set the width and height property after the image is loaded. Instead of using timeouts, I would recommend using an image’s onload event. If you write the code to load images while page is loading at that time you cannot get the real width and height of the image, you will get 0 as return value from width and height properties.

Here’s a quick jQuery example:


var img = $("img")[0]; // Get my img elem
var pic_width, pic_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_width = this.width; // Note: $(this).width() will not
pic_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.

You can also use the naturalHeight and naturalWidth HTML5 attributes.

For image resizing in front end i have already written an article which you can see in  Image resizing client-side with javascript before upload to the server but this article is used timeout function to read width and height of the image.

You may also like...