How to get the natural dimensions of an image using JavaScript or jQuery?
P粉916553895
P粉916553895 2023-10-21 13:53:08
0
2
783

So far I have this code:

var img = document.getElementById('draggable');
var width = img.clientWidth;
var height = img.clientHeight;

However, this gets me the html attribute - css style. I want to get the dimensions of the actual image resource of the file.

I need this because after uploading the image, its width is set to 0px and I don't know why or where this happens. To prevent this, I want to get the actual dimensions and reset them. is it possible?

EDIT: Even when I try to get the naturalWidth, the result is 0. I added a picture. The strange thing is that this only happens when I upload a new file and after a refresh it works fine.

http://oi39.tinypic.com/3582xq9.jpg

P粉916553895
P粉916553895

reply all(2)
P粉239164234

There are img.naturalHeight and img.naturalWidth which give you the width and height of the image itself, not the DOM element.

P粉148434742

You can use naturalWidth and naturalHeight, these properties contain the actual, unmodified width and height of the image, but you must wait until the image loads to get them

var img = document.getElementById('draggable');

img.onload = function() {
    var width  = img.naturalWidth;
    var height = img.naturalHeight;
}

This feature only supports IE9 and above, if you must support older browsers, you can create a new image, set its source to the same image, if the size of the image is not modified, it will return the natural size of the image , as this will be the default size when no other size is given

var img     = document.getElementById('draggable'),
    new_img = new Image();

new_img.onload = function() {
    var width  = this.width,
        heigth = this.height;
}

new_img.src = img.src;

FIDDLE

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template