Press "Enter" to skip to content

React 通过图片链接,打包下载图片

jszip file-saver

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);

One Comment

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注