【vue】vue将一批图片打包下载


<template>
  <div>
    <el-button @click="zip(arr)">arr</el-button>
   <el-button @click="zip(arr1)">arr1</el-button>
  </div>
</template>
<script>
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
export default {
  data() {
    return {
      arr: [{ picName: '图片名字', picUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Farticle-fd.zol-img.com.cn%2Ft_s998x562c5%2Fg5%2FM00%2F0A%2F02%2FChMkJltpVKGIQENcAAKaC93UFtUAAqi5QPdcOwAApoj403.jpg&refer=http%3A%2F%2Farticle-fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639737146&t=96efdde36bc7cd05972cad237e23dae6' }],
      arr1: [{ picName: '图片名字', picUrl: 'https://img0.baidu.com/it/u=3615671255,1670014403&fm=253&fmt=auto&app=138&f=JPEG?w=356&h=104' }]
    }
  },
  // created() {
  //   let arr = [{ picName: '图片名字', picUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Farticle-fd.zol-img.com.cn%2Ft_s998x562c5%2Fg5%2FM00%2F0A%2F02%2FChMkJltpVKGIQENcAAKaC93UFtUAAqi5QPdcOwAApoj403.jpg&refer=http%3A%2F%2Farticle-fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639737146&t=96efdde36bc7cd05972cad237e23dae6' }]
  //   this.zip(arr)
  // },

  methods: {
    zip(arr) {
      var zip = new JSZip();
      // 创建images文件夹
      var imgFolder = zip.folder("images");
      let flag = 0 //  判断加载了几张图片的标识

      for (let i = 0; i < arr.length; i++) {                  //遍历数组arr
        this.getBase64(arr[i].picUrl).then(base64 => {  //调用getBase64()方法,传入图片网络地址得到base64数据
          base64 = base64.split('base64,')[1]
          imgFolder.file(arr[i].picName + '.png', base64, { base64: true })//自定义图片名字,存进images文件夹里面
          if (flag === arr.length - 1) {
            zip.generateAsync({ type: "blob" }).then((blob) => {
              saveAs(blob, "压缩包名字.zip")//自定义文件压缩包名字
            })
          }
          flag++
        });
      }
    },


    //传入图片地址,返回base64格式数据
    getBase64(img) {
      var image = new Image();
      image.crossOrigin = '*';//解决图片跨域问题
      image.src = img;
      return new Promise((resolve, reject) => {
        image.onload = () => {
          resolve(this.getBase64Image(image));
        }
      })
    },

    //创建画布,将图片渲染到画布上,再将画布转为base64格式数据返回出来
    getBase64Image(img, width, height) {
      var canvas = document.createElement("canvas");
      canvas.width = width ? width : img.width;
      canvas.height = height ? height : img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      var dataURL = canvas.toDataURL();
      return dataURL;
    },
  }

}
</script>
<style lang="less" scoped>
.picture_download {
  display: flex;
  flex-flow: column;
  height: 100%;
}

.waterfall_active {
  background-color: red;
  border: 1px solid red;
}
</style>

你可能感兴趣的:(前端,vue,vue.js,javascript,前端)