在Javascript中获取图像的高度/宽度(理想情况下,根本不加载图像)

Ric*_*ard 16 javascript

很抱歉,如果已经回答了这个问题,但是如果是这样的话我就找不到了.

我想在Javascript中找到图像文件的高度和宽度.我实际上不需要在页面中显示图像,只需要显示高度和宽度.

目前我已经得到了以下代码,但它返回高度和宽度0(在Mozilla 5中).

  var img = new Image();
  img.src = "./filename.jpg";
  var imgHeight = img.height;
  var imgWidth = img.width;
  alert("image height = "  + imgHeight + ", image width = " + imgWidth);
Run Code Online (Sandbox Code Playgroud)

该文件肯定存在,它与HTML在同一目录中,并且它没有高度和宽度0 :)

我究竟做错了什么?

luv*_*ere 20

如果未加载图像,则不会设置其高度和宽度.您必须等到图像完全加载,然后检查其大小.也许是这些方面的东西:

function getWidthAndHeight() {
    alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
    return true;
}
function loadFailure() {
    alert("'" + this.name + "' failed to load.");
    return true;
}
var myImage = new Image();
myImage.name = "image.jpg";
myImage.onload = getWidthAndHeight;
myImage.onerror = loadFailure;
myImage.src = "image.jpg";
Run Code Online (Sandbox Code Playgroud)


ale*_*emb 8

以下代码将为您提供宽度/高度,而无需等待图像完全加载,使其明显快于此处的其他解决方案.

用于测试将abc123图像源更改为任何随机字符串以防止缓存.

还有一个JSFiddle演示.

<div id="info"></div>
<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Island_Archway,_Great_Ocean_Rd,_Victoria,_Australia_-_Nov_08.jpg?abc123">

<script>
getImageSize($('#image'), function(width, height) {
    $('#info').text(width + ',' + height);
});

function getImageSize(img, callback) {
    var $img = $(img);

    var wait = setInterval(function() {
        var w = $img[0].naturalWidth,
            h = $img[0].naturalHeight;
        if (w && h) {
            clearInterval(wait);
            callback.apply(this, [w, h]);
        }
    }, 30);
}
</script>
Run Code Online (Sandbox Code Playgroud)

  • 有趣的方法.是否在规范中记录了浏览器将尽快设置naturalWidth和naturalHeight,或者这仅仅是某些实现的副作用?你对这种方法有什么参考吗? (6认同)

Luc*_*125 5

图像元素的高度和宽度属性(如任何元素的 offsetHeight 和 offsetWidth 属性),返回 0 而不是实际值,直到它被添加到某个文档(如果它的 style.display 属性没有设置为“none ”)。
解决此问题的常用方法是在页面可见区域之外显示图像;你的用户不会看到它,它的高度和宽度属性将返回实际值而不是 0。然后你应该从文档中删除图像。

var img = new Image();
img.src = "./filename.jpg";
img.style.position = "absolute";
img.style.left = -9999;             // Image width must not exceed 9999 pixels
img.style.visibility = "hidden";    // Maybe you can remove this
document.body.appendChild(img);
var imgHeight = img.height;
var imgWidth = img.width;
alert("image height = "  + imgHeight + ", image width = " + imgWidth); 
document.body.removeChild(img);     // Removes the image from the DOM (This does not destroy the image element)
Run Code Online (Sandbox Code Playgroud)