【问题标题】:Getting the original size of a scaled image [duplicate]获取缩放图像的原始大小[重复]
【发布时间】:2012-01-24 15:35:02
【问题描述】:

如果我的图像是这样的:<img src="picture.png" style="max-width:100px">,我如何从 javascript 中获取原始的、未缩放的图像大小?

我找到了我的答案,你可以使用img.naturalWidth得到原来的宽度

var img = document.getElementsByTagName("img")[0];
img.onload=function(){
    console.log("Width",img.naturalWidth);
    console.log("Height",img.naturalHeight);
}

Source

【问题讨论】:

  • @bugster 我们如何实现这个以获取网站中缩放图像的原始大小?如果无法访问该网站,那么如何获取原始图像呢?考虑到原始图片 url 是一个公共链接。

标签: javascript


【解决方案1】:

编辑:如果您想在图像呈现在页面上之后、但在使用比例转换其大小之前检索计算出的图像大小,则此方法很有用。如果你只想要图片的原始大小,使用上面的方法。

在缩放时尝试将图像的比例写入数据属性。然后,您可以轻松地将新尺寸除以该比例属性以检索原始尺寸。它可能看起来像这样:

// Set the scale data attribute of the image
var scale = 2;
img.dataset.scale = scale;

...

// Later, retrieve the scale and calculate the original size of the image
var s = img.dataset.scale;
var dimensions = [img.width(), img.height()];
var originalDimensions = dimensions.map(function(d) {return d / parseFloat(s)});

或者,您可以直接使用 jQuery 和正则表达式检索图像的比例。

var r = /matrix\(([\d.]+),/;
try {
  var currentTransform = $swiper.css('transform');
  var currentScale = currentTransform.match(r)[1];
}
// Handle cases where the transform attribute is unset
catch (TypeError) {
  currentScale = 1;
}

这比创建一个全新的图像并依靠浏览器的缓存来快速加载对我来说更直观。

【讨论】:

  • 如果图像按<img> 标记中的参数缩放,这将不起作用。图片具有.naturalWidth.naturalHeight 属性,可让您直接获取原始尺寸。
  • 我明白了。对于我的用例,我需要的不是图像的原始尺寸,而是在缩放之前在页面上呈现的图像大小。由于我正在调整具有不同原始大小的图像以适应 div,.naturalWidth.naturalHeight 属性对我不起作用,但这种方法可以。你介意我留下这个答案,以防有人来这里遇到和我一样的问题,还是我应该把它拿下来?
【解决方案2】:

一种方法是创建另一个图像元素,将其 src 设置为原始的 src,然后读取其宽度。这应该很便宜,因为浏览器应该已经缓存了图像。

var i = document.getElementById('myimg');

var i2 = new Image();
i2.onload = function() {
   alert(i2.width);
};

i2.src = i.src;

这是一个小提琴:http://jsfiddle.net/baZ4Y/

【讨论】:

  • 我也是这样做的,但是创建一个包含图像数据的新对象,并依靠浏览器的内部缓存机制不让事情陷入困境,这对我来说似乎是一种浪费。必须有更好的方法。
  • Pekka 指出这个问题之前已经得到了回答,这也是那个问题的方法。可能这只是浏览器/JS 没有很好的处理机制的一个小边缘案例。
猜你喜欢
  • 2015-11-15
  • 2016-06-09
  • 1970-01-01
  • 2023-01-14
  • 2020-11-14
  • 2017-06-10
  • 2015-02-14
  • 1970-01-01
  • 2012-08-28
相关资源
最近更新 更多