Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the original size of a scaled image [duplicate]

Tags:

javascript

How can I get the original, unscaled, size of an image from javascript if my image is like this: <img src="picture.png" style="max-width:100px">?

I found my answer, you can use img.naturalWidth to get the original width

var img = document.getElementsByTagName("img")[0];
img.onload=function(){
    console.log("Width",img.naturalWidth);
    console.log("Height",img.naturalHeight);
}

Source

like image 283
Bugster Avatar asked Oct 09 '22 04:10

Bugster


1 Answers

One way to do it is to create another image element, set its src to the original's src, and then reading its width. This should be inexpensive as the browser should have already cached the image.

var i = document.getElementById('myimg');

var i2 = new Image();
i2.onload = function() {
   alert(i2.width);
};

i2.src = i.src;

Here is a fiddle: http://jsfiddle.net/baZ4Y/

like image 89
Matt Greer Avatar answered Oct 13 '22 11:10

Matt Greer