Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an image's original width and height in jQuery

I need to get the original width and height of an image given a specific source. My current method is:

img.tag = "<img style='display:none;' src='" + img.src + "' />";
img.Owidth = 0;
img.Oheight = 0;

$(img.tag).load(function() {
    img.Owidth = $(this).width();
    img.Oheight = $(this).height();
}).appendTo(img.parent());

With Owidth and Oheight being the original dimensions of the loaded image. I'm wondering if there is a better way to do this given that:

  • The image could either already be loaded, but displayed at a different size than its original size.
  • The image has not yet been loaded at all
like image 440
Joey Avatar asked Jul 16 '12 22:07

Joey


2 Answers

For Chrome and Firefox (and hopefully IE soon), you can use...

var width = $('img').prop('naturalWidth');
var height = $('img').prop('naturalHeight');
like image 80
alex Avatar answered Nov 01 '22 16:11

alex


Cross-Browser:

jsFiddle demo

$("<img/>").load(function(){
    var width  = this.width,
        height = this.height; 
    alert( 'W='+ width +' H='+ height);
}).attr("src", "image.jpg");

HTMLImageElement properties / HTML5 compliant browsers

If you want to investigate about all the HTMLImageElement properties: https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
Many of those properties are available already in modern, HTML5 compliant browsers, and accessible using jQuery's .prop() metod

jsFiddle demo

var $img = $("#myImage");

console.log(
    $img.prop("naturalWidth") +'\n'+  // Width  (Natural)
    $img.prop("naturalHeight") +'\n'+ // Height (Natural)
    $img.prop("width") +'\n'+         // Width  (Rendered)
    $img.prop("height") +'\n'+        // Height (Rendered)
    $img.prop("x") +'\n'+             // X offset
    $img.prop("y")                    // Y offset ... 
);
like image 19
Roko C. Buljan Avatar answered Nov 01 '22 16:11

Roko C. Buljan