Home  >  Q&A  >  body text

How to get the natural dimensions of an image using JavaScript or jQuery?

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粉916553895P粉916553895257 days ago421

reply all(2)I'll reply

  • P粉239164234

    P粉2391642342023-10-22 13:03:59

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

    Reply
    0
  • P粉148434742

    P粉1484347422023-10-22 09:42:28

    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

    Reply
    0
  • CancelReply