Javascript可以访问原生图像大小吗?

我正在编写一个jQuery函数,我想访问图像的原生大小,以及页面上为其指定的大小。 我想为每个设置一个变量。

怎么做的?

现代浏览器

当我在2009年写回这个答案时,浏览器的格局就大不相同了。 现在任何合理的现代浏览器都支持使用img.naturalWidthimg.naturalHeight Pim Jager的建议 。 看看他的回答。

传统答案与超级旧浏览器兼容

 // find the element var img = $('#imageid'); /* * create an offscreen image that isn't scaled * but contains the same image. * Because it's cached it should be instantly here. */ var theImage = new Image(); theImage.src = img.attr("src"); // you should check here if the image has finished loading // this can be done with theImage.complete alert("Width: " + theImage.width); alert("Height: " + theImage.height); 

这应该工作:

 var img = $('#imageid')[0]; //same as document.getElementById('imageid'); var width = img.naturalWidth; var height = img.naturalHeight; 

naturalWidth和naturalHeight返回图像响应的大小,而不是显示大小。

根据Josh的评论,这不支持跨浏览器,这可能是正确的,我在FF3中测试了这个

编辑 – 新想法…请参阅http://jsbin.com/uzoza

  var fixedW = $("#imageToTest").width(); $("#imageToTest").removeAttr("width"); var realW = $("#imageToTest").width(); $("#imageToTest").attr("width", fixedW); 

原始答案

请参阅如何使用JavaScript获取图像大小(高度和宽度)?

 var img = $('#imageid'); var width = img.clientWidth; var height = img.clientHeight; 

我正在添加一种方法来实现这一点,并确保支持所有浏览器。 几乎所有浏览器都支持naturalWidthnaturalHeight ,Internet Explorer 8及以下naturalHeight除外。

由于IE 8及以下版本在使用尝试检索大小值时会返回可见图像的大小而不是自然大小,因此需要一个小的解决方法来获得Jack Moore的示例中的完整大小维度。

 function naturalSize(imageid) { imageid = (imageid.src ? imageid : document.getElementById(imageid)); if (document.documentMode < 9) { var img = new Image(); img.src = imageid.src; return {width: img.width,height: img.height}; } return {width: imageid.naturalWidth,height: imageid.naturalHeight}; } 

我将其设置为支持传递图像ID值或ID的名称。

用法:

  naturalSize("some_img"); // Returns: Object {width: 731, height: 387} 

要么

  // Displays: Size: 731x387 

在调用之前确保图像已加载,无论是使用onload还是在将其添加到DOM时触发。

测试:Windows XP - Firefox 1.5,IE 8 Windows 7 - IE 9,Chrome 56 Android 6.0.1 - Chrome 50 Android 5.1.1 - Opera Mini 7.6,Dolphin 10.3

完整代码示例:

            

我的解决方案是编写一个获取/下载图像的Web服务,然后获取其分辨率并将其返回为{width:x,height:y}。 然后用$ .ajax或等效的方法调用它来检索它。

或者,您可以使用将图像添加到隐藏的div中

 // eg don't set width and height $("#hiddendiv").html(""); 

然后得到div的宽度/高度,虽然我没有尝试过。