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="" 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.