【问题标题】:Get the width of an image specified by an url jquery获取由 url jquery 指定的图像的宽度
【发布时间】:2012-01-28 00:59:39
【问题描述】:

我想在 for 循环中读取由 url 指定的图像的宽度 (orgWidth),计算其新宽度 (calcWidth) 为 480 像素的高度。

for (var i=1; i <= item.length; i++) {

    url = document.images[i].rsc;
    orgWidth = some-fancy-thing-that-reads-the-width;
    orgHeight = some-fancy-thing-that-reads-the-height;

    factor = orgHeight / 480        // 1400 / 480 = 2.916
    calcWidth = orgWidth / factor       // 1000 / 2.916 = 342.935

    document.images[i].width = calcWidth;

}

我需要它的页面: http://foto.hendrik-schicke.de/index.php/people

【问题讨论】:

标签: jquery


【解决方案1】:

这在使用 javascript 时是不可能的,通过“非预加载”当然也不可能,因为您需要“拥有”文件才能对其进行处理。

您最好的方法是将图像的 URL 传递给服务器端脚本(PHP?),该脚本将获取图像尺寸并将数据传回给您或将其存储在数据库中(这里的可能性是无穷无尽的) .

但要回答您的问题,纯 javascript 不加载图像是不可能的。

【讨论】:

  • 有没有办法通过预加载来做到这一点,但要使用声称的功能?
【解决方案2】:
var tmpImg = new Image();
tmpImg.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png"; //or  document.images[i].src;
$(tmpImg).on('load',function(){
  var orgWidth = tmpImg.width;
  var orgHeight = tmpImg.height;
  alert(orgWidth+"x"+orgHeight);
});

演示:http://jsfiddle.net/eWzWg/3/

【讨论】:

  • 您的演示和我的页面为 orgWidth 和 orgHeight 返回 0。 :(
  • 图像加载似乎需要时间,请尝试编辑后的答案,jsfiddle.net/eWzWg/3
  • 适用于此示例,但不适用于我的页面。在 for 循环完成后,“$(tmpImg).one('load',function(){”部分开始。见:jsfiddle.net/eWzWg/10
  • 为什么循环实际上是for?
【解决方案3】:

我们可以检查图像是否已经加载到浏览器的缓存中。只有当图像被加载时,我们才会将 onload 处理程序绑定到它。这是纯 javascript 示例。

var image;
function onload () {
    console.log(image.height, image.width);
}

image= new Image();
image.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png";
// check if image is already loaded to cache
if (image.complete) {
    console.log('image already loaded to browser');
    onload();
} else {
    // or bind onload handler for image
    image.onload = onload;
}

jsFiddle 上玩这个例子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 2014-07-06
    • 2012-12-11
    • 2012-07-11
    • 2012-04-04
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多