Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full size of image in javascript/jquery

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.

like image 872
emc Avatar asked Mar 09 '12 09:03

emc


People also ask

How can get image width and height in jquery?

width(); alert(imageWidth); var imageHeight = Imgsize. height();

How do you get the image width and height using JS?

Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.


1 Answers

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

like image 71
adeneo Avatar answered Oct 19 '22 23:10

adeneo