How do I get natural dimensions of an image using javascript or jquery?

雨燕双飞 提交于 2019-11-28 11:53:29

You could use naturalWidth and naturalHeight, these properties contain the actual, non-modified width and height of the image, but you have to wait until the image has loaded to get them

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

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

This is only supported from IE9 and up, if you have to support older browser you could create a new image, set it's source to the same image, and if you don't modify the size of the image, it will return the images natural size, as that would be the default 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

mash

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

You can use the following function I made.

Function

function getImageDimentions(imageNode) {
  var source = imageNode.src;
  var imgClone = document.createElement("img");
  imgClone.src = source;
  return {width: imgClone.width, height: imgClone.height}
}

html:

<img id="myimage" src="foo.png">

use it like this

var image = document.getElementById("myimage"); // get the image element
var dimentions = getImageDimentions(image); // get the dimentions
alert("width: " + dimentions.width + ", height: " + dimentions.height); // give the user a visible alert of the dimentions
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!