javascript - Javascript:在一个请求中获取图像的尺寸和大小
问题描述
基于此处的其他帖子,我写了这个来获取文件的尺寸和大小
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';
虽然它有效,但我想知道我是否可以将两者合二为一,这意味着只做the或Image onLoad
requestxhr
吗?
解决方案
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
回调,因为浏览器需要一些时间来解析图像,但在这种情况下,它不会导致网络往返。
推荐阅读
- java - JFileChooser 的 FileFilter 有编译错误
- python - 为什么在刷新数据库更改后 SQLAlchemy 将字符串更改为整数?
- java - java中的碰撞检测问题。intersectsWith 方法总是返回 true
- reactjs - Gatsby-remark-images 偶尔会链接图像
- c++ - 如何将 boost 设置为不同的版本?
- animation - 如何达到缩小画面的效果?
- python - 为什么 Visual Studio Code 将“return super().__init__(self)”插入派生类?
- node.js - 如何在 node.js 中发出 HTTPS POST 请求?
- firebase - 如何将图像上传到firebase存储中的文件夹
- java - 如何仅在拇指移动时设置 SeekBar 值?