gpt4 book ai didi

Javascript:在一个请求中获取图像的尺寸和大小

转载 作者:行者123 更新时间:2023-12-01 16:18:03 25 4
gpt4 key购买 nike

根据这里的其他帖子,我写了这个来获取文件的尺寸和大小

    const newImg = new Image();

newImg.onload = () => {
console.log('height ' + newImg.height);
console.log('width ' + newImg.width);

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.google.com/myImage.png', true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log('size ' + this.response.byteLength);
}
};
xhr.send(null);
}

newImg.src = 'https://www.google.com/myImage.png';

虽然它有效,但我想知道我是否可以将两者合而为一,这意味着Image onLoadxhr 请求?

最佳答案

您可以使用 Blob 避免第二次网络往返和一个 data URI :

fetch('https://cdn.glitch.com/2eddb7d4-12e2-45ae-8d27-738f13fb514a%2FGOPR1017_1586689900523.JPG?v=1587457335788')
.then(r => r.arrayBuffer())
.then(buffer => {
console.log('Size: ' + buffer.byteLength)
const blob = new Blob([buffer], {type: 'image/jpeg'})
const img = new Image()
img.src = URL.createObjectURL(blob)
img.onload = function() {
console.log(img.width, img.height)
}
})

请注意,您仍然需要 onload 回调,因为浏览器需要一些时间来解析图像,但在这种情况下,它不会导致网络往返。

关于Javascript:在一个请求中获取图像的尺寸和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61316218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com