HTML, jQUERY find actual size of image in img tag


Basically using DOM functions, if we try and get the size of <img />, we always get the dimensions of DOM element, not the actual image.

To be able to get actual size of image, we will have to reload it in a new <img /> without any size restriction. If we do that, this new <img /> will take dimensions of actual image, and using simple DOM methods we can get the actual size of image.

Sample HTML

<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-desktop-1440x900-a.png" width="480" height="300">

JS trick

function getImageSize(url, callback){
    $('<img />').attr('src', url).load(function(){
        callback(this.width, this.height);
    });
}
getImageSize($("img").attr('src'), function(width, height){
        console.log(width, height);
});

Try this on JSFIDDLE.

HTML5 Update

HTML5 has introduced a much easier way of doing the same thing. If your browser supports HTML5, ignore the previous method and use this one.

$("img")[0].naturalWidth
$("img")[0].naturalHeight
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s