0

Possible Duplicate:
Determine original size of image cross browser?
jquery get image size

could someone tell me how do i get the real size of an image using JS / JQ ? THX ! tried a lot of solutions from this site but no success...

var selector = $(".album_pics > img[id="+img_id+"]") ;
var old_width = selector.width() ;

Doesnt work..

Community
  • 1
  • 1
Mor Cohen
  • 101
  • 1
  • 9

1 Answers1

9

You can use the naturalWidth property:

var img = document.getElementById('imageToTest'), // or whatever...
    width = img.naturalWidth;

JS Fiddle demo.

This does, of course, require that the image has time to load before the JavaScript is executed (so, in jQuery, using the $(window).load() method). It is, also, HTML5-only (which I hadn't realised until I checked, just now).

Incidentally, as perhaps the name implies, there's also the naturalHeight property (if that would be of use).

Updated to add a slightly more functional approach:

function showNaturalInfo(el) {
    if (!el || el.tagName.toLowerCase() !== 'img') {
        return false;
    }
    else {
        var w = el.naturalWidth,
            h = el.naturalHeight,
            D = document,
            details = D.createElement('span'),
            detailsText = D.createTextNode('Natural width: ' + w + 'px; natural height: ' + h + 'px.');
        details.appendChild(detailsText);
        el.title = 'Natural width: ' + w + 'px; natural height: ' + h + 'px.';
        el.parentNode.insertBefore(details, el.nextSibling);
    }
}

var imgs = document.getElementsByTagName('img');

for (var i = 0, len = imgs.length; i < len; i++) {
    showNaturalInfo(imgs[i]);
}​

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 2
    I am slightly curious as to the down-vote. I know they're occasionally somewhat random, but it'd be *nice* to know if I'd suggested something wrong, or spectacularly useless for someone. Sigh... =/ – David Thomas Sep 23 '12 at 21:39