在图像完全加载之前使用 Javascript 获取图像尺寸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6575159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:21:01  来源:igfitidea点击:

Get image dimensions with Javascript before image has fully loaded

javascriptimageloadingdimensions

提问by user828591

I've read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just started to load?

我已经阅读了有关在图像完全加载后获取图像尺寸的各种方法,但是一旦开始加载,是否有可能获得任何图像的尺寸?

I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.

我没有通过搜索找到太多相关信息(这让我相信这是不可能的),但事实上浏览器(在我的例子中是 Firefox)显示了我在标题中的新标签页中打开的任何图像的尺寸它刚刚开始加载图像让我希望实际上有一种方法,而我只是错过了找到它的正确关键字。

回答by katspaugh

You are right that one can get image dimensions before it's fully loaded.

您是对的,可以在完全加载之前获取图像尺寸。

Here's a solution (demo):

这是一个解决方案(演示):

var img = document.createElement('img');

img.src = 'some-image.jpg';

var poll = setInterval(function () {
    if (img.naturalWidth) {
        clearInterval(poll);
        console.log(img.naturalWidth, img.naturalHeight);
    }
}, 10);

img.onload = function () { console.log('Fully loaded'); }

回答by aleemb

The following code returns width/height as soon as it's available. For testing change abc123in image source to any random string to prevent caching.

以下代码在可用时立即返回宽度/高度。用于测试将abc123图像源更改为任何随机字符串以防止缓存。

There is a JSFiddle Demoas well.

还有一个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>

回答by Saeed Neamati

One way is to use the HEAD request, which asks for HTTP Header of the response only. I know in HEAD responses, the size of the body is included. But I don't know if there anything available for size of images.

一种方法是使用 HEAD 请求,它只要求响应的 HTTP 标头。我知道在 HEAD 响应中,包括身体的大小。但我不知道是否有任何可用的图像大小。