在图像完全加载之前使用 Javascript 获取图像尺寸
我读过有关在图像完全加载后获取图像尺寸的各种方法,但是一旦开始加载就可以获取任何图像的尺寸吗?
我还没有通过搜索找到太多相关信息(这让我相信这是不可能的),但事实是浏览器(在我的例子中是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你是对的,人们可以在图像完全加载之前获取图像尺寸。
这是一个解决方案(演示):
You are right that one can get image dimensions before it's fully loaded.
Here's a solution (demo):
以下代码在宽度/高度可用时立即返回。为了测试,将图像源中的
abc123
更改为任意随机字符串以防止缓存。还有一个 JSFiddle 演示。
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.
您可以使用
ResizeObserver
实现此目的,请参阅 https://codepen。 io/noamr/pen/NWOaqjp?editors=1111
You can achieve this with
ResizeObserver
See https://codepen.io/noamr/pen/NWOaqjp?editors=1111
一种方法是使用 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.
在将图像附加到 DOM 之前,无法获取图像大小,除非您解码响应并检查图像元数据,如下所述: https://stackoverflow.com/a/74710020/7134134
一个更简单的替代方案是附加元素,获取所需的数据并立即删除它:
整个过程运行由于浏览器的工作方式而异步。
编辑:虽然没有太大区别,但
ResizeObserver
回调是在 onload 事件之前执行的,因此使用ResizeObserver
可能会好一点。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:
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 useResizeObserver
.