使用Javascript下载图像并将其转换为Blob

Download image with Javascript and convert it to a Blob

本文关键字:转换 Blob Javascript 下载 图像 使用      更新时间:2023-09-26

使用HTML5和FileReader/Blob,我可以从/转换为Blobs/dataURI,但我想知道是否可以从远程URL下载图像并将其转换为Blob(或dataURI)。

如果这是可能的,我该怎么做?

我自己设法做到了:

var xhr = new XMLHttpRequest();
xhr.open('GET', attr.ngfDefaultSrc, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
   if (this.status !== 200) return;
   var blob = new Blob([this.response], {type: this.response.type});
   //rest of the code that uses the blob goes here
};
xhr.send();