9

I have an image on page that has been resized to fit in a div, say, 400x300. How can I get the full size of the image (~4000x3000) in jQuery? .width() and .height() only seem to return the current size of the image.

emc
  • 507
  • 1
  • 7
  • 25

4 Answers4

22

Images have naturalWidth and naturalHeight properties that contain the actual, non-modified width and height of the image, i.e. the real dimensions of the image, not what CSS sets it to.

One would still have to wait for the image to load though

$('#idOfMyimg').on('load', function() {
    var height = this.naturalHeight,
        width  = this.naturalWidth;
});

Another option would be to create a new image with the same file as the source, and get the dimensions from that, as long as it's never added to the DOM, not external styles will affect it

var img = new Image();

img.onload = function() {
   var height = this.height,
       width  = this.width;
}
img.src = $('#idOfMyimg').attr('src');

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
4

You can clone the image, remove the height and width attributes, append it to the body and get the width and size before removing it.

jsFiddle demo is here: http://jsfiddle.net/58dA2/

Code is:

$(function() {
   var img = $('#kitteh'); // image selector
   var hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
    $('#height').text(hiddenImg.height());
    $('#width').text(hiddenImg.width());
    hiddenImg.remove();            
});​
GregL
  • 37,147
  • 8
  • 62
  • 67
1

You can do this with an Image object that holds the same source file like:

var preloader = new Image();
preloader.src = 'path/to/my/file.jpg';

preloader.onload = function(){
var height = preloader.height;
var width = preloader.width;
}
m90
  • 11,434
  • 13
  • 62
  • 112
-2

Try this:

var pic = $("img")

// need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height");

var pic_real_width = pic.width(); var pic_real_height = pic.height();

Java
  • 2,451
  • 10
  • 48
  • 85
  • I have edited my answer, now it will work plz check at ur [jsfiddle.net/kCN2x] link – Java Mar 09 '12 at 09:50