下载图片作为 zip 包
import JsZip from 'jszip'
import saveAs from 'file-saver'
function getBase64Image(img, width, height) {
const canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL();
return dataURL;
}
function getBase64FromUrl(url) {
return new Promise((resolve, reject) => {
if(!url) reject('url 为空')
const image = new Image();
image.crossOrigin = 'Anonymous';
image.src = url;
image.onload = function (){
resolve(getBase64Image(image));
}
})
}
async function saveZip (base64Arr) {
const zip = new JsZip()
const imagesFolder = zip.folder("images")
for(var i = 0; i < base64Arr.length; i++) {
const item = base64Arr[i]
imagesFolder.file(item.url, item.base64, { base64: true });
}
zip.file("说明.txt", "本压缩包共包含 " + base64Arr.length + " 张图片,如果下载文件数量不足 " + _length + " 张,请尝试重新下载");
const content = await zip.generateAsync({ type:"blob" })
saveAs(content, "图片.zip")
}
async function downFiles (imageUrls) {
const base64Arr = []
for (let i = 0; i < imageUrls.length; i++) {
let url = imgUrls[i]
const base64 = await getBase64FromUrl(url)
base64Arr.push({ url, base64: base64.split(',')[1] });
}
saveZip(base64Arr)
}