2012-04-26 65 views
2

正在寻找一种获取外部图像的尺寸(宽度和高度)的方式。
我已经使用prop()attr(),但它们不返回任何值。只是一个错误。jQuery:如何获取外部图像的尺寸?

例子:

<a href="pathtotheimage">some link</a> 
+2

你唯一的办法就是装载图像。 (如果你使用JavaScript) – 2012-04-26 17:45:26

+0

啊有道理,不能得到尺寸,如果图像没有加载。谢谢 – user759235 2012-04-26 20:28:31

回答

9
var imgSrc = "http://server.com/your/image/path/here.jpg" 
var _width, _height; 
$("<img/>").attr("src", imgSrc).load(function() { 
    _width = this.width; 
    _height = this.height; 
}); 
+1

如果图像从浏览器缓存中提取,'.load'事件不会触发。请参阅[此问题](http://stackoverflow.com/q/3877027/901048)了解解决方案。 – Blazemonger 2012-04-26 18:12:51

-1

这不是技术上的jQuery但我会往下走的路线:使用widthheight

var image = new Image(), width, height; 
image.src = 'http://whereyourimage.is/heresmyimage.jpg'; 
width = image.width; 
height = image.height; 

然后,您可以访问这些值,例如alert('My image is ' + width + ' pixels accross.');

+2

这是行不通的,因为您在设置src的同时访问宽度,因此浏览器无法提供正确的信息。 – Esailija 2012-04-26 17:55:18

+0

为我工作,但我刚刚意识到图像被缓存!傻子!当我回到电脑时将编辑答案 – freshnode 2012-04-26 18:50:38

1

看起来像没有提供了一个工作香草JS答案。

var img = document.createElement('img') 
img.src = 'http://domain.com/img.png' 
img.onload = function() { 
    console.log(this.width) 
    console.log(this.height) 
} 

这里是一个的jsfiddle:http://jsfiddle.net/Ralt/VMfVZ/