Get full image size in javascript / jquery

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

+8
javascript jquery image resize
source share
4 answers

Images have the naturalWidth and naturalHeight , which contain the actual, unmodified width and height of the image, i.e. real image sizes, not what CSS sets.

It would remain to wait for the image to load, although

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

Another option is to create a new image with the same file as the source, and get dimensions from it if it is never added to the DOM, and 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

+21
source share

You can clone an image, remove the height and width attributes, add it to the body and get the width and size before deleting.

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

The code:

 $(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(); });​ 
+4
source share

You can do this using the Image object, which contains the same source file as:

 var preloader = new Image(); preloader.src = 'path/to/my/file.jpg'; preloader.onload = function(){ var height = preloader.height; var width = preloader.width; } 
+1
source share

Try the following:

var pic = $ ("img")

// you need to remove them if the img element has set the width and height pic.removeAttr ("width"); pic.removeAttr ("height");

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

-2
source share

All Articles