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

发布于 2024-11-18 16:19:51 字数 182 浏览 2 评论 0原文

我读过有关在图像完全加载后获取图像尺寸的各种方法,但是一旦开始加载就可以获取任何图像的尺寸吗?

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

闻呓 2024-11-25 16:19:51

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

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

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'); }

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'); }
彩扇题诗 2024-11-25 16:19:51

以下代码在宽度/高度可用时立即返回。为了测试,将图像源中的 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>

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

There is a JSFiddle Demo as well.

<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>
土豪我们做朋友吧 2024-11-25 16:19:51

您可以使用 ResizeObserver 实现此目的,

new ResizeObserver((e, observer) => {
  img.remove();
  observer.disconnect();
  console.log(`${img.naturalWidth},${img.naturalHeight}`);
}).observe(img);
document.body.appendChild(img);

请参阅 https://codepen。 io/noamr/pen/NWOaqjp?editors=1111

You can achieve this with ResizeObserver

new ResizeObserver((e, observer) => {
  img.remove();
  observer.disconnect();
  console.log(`${img.naturalWidth},${img.naturalHeight}`);
}).observe(img);
document.body.appendChild(img);

See https://codepen.io/noamr/pen/NWOaqjp?editors=1111

信仰 2024-11-25 16:19:51

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

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.

热情消退 2024-11-25 16:19:51

在将图像附加到 DOM 之前,无法获取图像大小,除非您解码响应并检查图像元数据,如下所述: https://stackoverflow.com/a/74710020/7134134

一个更简单的替代方案是附加元素,获取所需的数据并立即删除它:

async function getImageDimentions(src: string) {  
  return new Promise(resolve => {
    const img = new Image();
    img.src = src;
    document.body.appendChild(img);
    img.onload = () => {
      img.remove();
      resolve({ width: img.naturalWidth, height: img.naturalHeight });
    };
  });
}

整个过程运行由于浏览器的工作方式而异步。

编辑:虽然没有太大区别,但 ResizeObserver 回调是在 onload 事件之前执行的,因此使用 ResizeObserver 可能会好一点。

async function getImageDimentions(src: string) {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = src;
    new ResizeObserver((_e, observer) => {
      img.remove();
      observer.disconnect();
      if (img.naturalWidth) resolve({ width: img.naturalWidth, height: img.naturalHeight });
    }).observe(img);
    document.body.appendChild(img);
  });
}

There is no way to get the image size until it is attached to the DOM unless you decode the response and check the image metadata, which is explained here: https://stackoverflow.com/a/74710020/7134134

A simpler alternative would be appending the element, getting the required data and removing it immediately:

async function getImageDimentions(src: string) {  
  return new Promise(resolve => {
    const img = new Image();
    img.src = src;
    document.body.appendChild(img);
    img.onload = () => {
      img.remove();
      resolve({ width: img.naturalWidth, height: img.naturalHeight });
    };
  });
}

The whole thing runs asynchronously because of the way browser works.

Edit: Although it does not make much difference, the ResizeObserver callback is executed before the onload event, so it may be a little better to use ResizeObserver.

async function getImageDimentions(src: string) {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = src;
    new ResizeObserver((_e, observer) => {
      img.remove();
      observer.disconnect();
      if (img.naturalWidth) resolve({ width: img.naturalWidth, height: img.naturalHeight });
    }).observe(img);
    document.body.appendChild(img);
  });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文