如何使用javascript或jquery获取图像的自然尺寸?

use*_*605 26 javascript jquery image dimensions

到目前为止我有这个代码:

var img = document.getElementById('draggable');
var width = img.clientWidth;
var height = img.clientHeight;
Run Code Online (Sandbox Code Playgroud)

然而,这让我获得了html属性--css样式.我想获得文件的实际图像资源的维度.

我需要这个,因为在上传图像时,它的宽度设置为0px,我不知道为什么或发生这种情况.为了防止它,我想获得实际尺寸并重置它们.这可能吗?

编辑:即使我尝试获得naturalWidth,我也会得到0.我添加了一张图片.奇怪的是,只有当我上传新文件并刷新它才能正常工作时才会发生这种情况.

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

ade*_*neo 47

你可以使用naturalWidthnaturalHeight,这些属性包含图像的实际,未修改的宽度和高度,但你必须等到图像加载后才能获得它们

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

img.onload = function() {
    var width  = img.naturalWidth;
    var height = img.naturalHeight;
}
Run Code Online (Sandbox Code Playgroud)

这只支持从IE9及以上,如果您必须支持旧浏览器,您可以创建一个新图像,将它的源设置为相同的图像,如果您不修改图像的大小,它将返回图像自然大小,因为没有给出其他大小时将是默认值

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;
Run Code Online (Sandbox Code Playgroud)

小提琴

  • 当jQuery DOM ready函数触发时,不加载图像,只有DOM准备就绪.`$(window).on('load')`会在所有内容都加载时触发,但只是将onload事件处理程序直接附加到图像上会更好IMO. (4认同)

mas*_*ash 18

img.naturalHeightimg.naturalWidth哪些给你图像本身的宽度和高度,而不是DOM元素.

  • 在IE8或更低版本中不起作用,据我所知,不在Opera中. (3认同)
  • 有趣.请注意,对于IE,这适用于IE9或更高版本.我查了一下,偶然发现了一个将`.naturalHeight()`和`.naturalWidth()`添加到jQuery的片段.我想我可以在这里分享这个信息:http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/ (2认同)

nat*_*olt 5

您可以使用我所做的以下功能。

功能

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

的HTML:

<img id="myimage" src="foo.png">
Run Code Online (Sandbox Code Playgroud)

这样使用

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
Run Code Online (Sandbox Code Playgroud)