import JSZip from "jszip";
import FileSaver from "file-saver";
const getBase64Image = (img) => {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
return canvas.toDataURL("image/" + ext);
};
const toZip = (imgSrcList = [], fileName = "") => {
let zip = new JSZip();
let imgFolder = zip.folder(fileName);
imgSrcList.forEach((src, i) => {
let tempImage = new Image();
tempImage.src = src;
tempImage.crossOrigin = "*";
tempImage.onload = () =>
imgFolder.file(i + 1 + ".jpg", getBase64Image(tempImage).substring(22), {
base64: true,
});
});
setTimeout(
() =>
zip
.generateAsync({ type: "blob" })
.then((blob) => FileSaver.saveAs(blob, `${fileName}.zip`)),
3000
);
};
export default toZip;
使用
toZip(imgSrcList, fileName);
拿走了代码