zoukankan      html  css  js  c++  java
  • vue 项目图片批量导出并压缩成zip

    1、安装依赖并引入

      npm install jszip --save

      npm install file-saver --save

      import JSZip from 'jszip'
      import FileSaver from 'file-saver'
    2、将远程或本地图片的url转换成base64,然后下载
     /**
       *多个图片压缩成zip导出
       */
     private downloadZip() {
       let that = this
       const zip = new JSZip()
       let arrs:any = [] // 这个数组只用于判断图片是否都转换成base64
       setTimeout(_ => {
         let arr = that.multipleSelections // 待转换的数据(包含图片的名和地址)
         arr.forEach((item:any) => {
           let fileName = item.orgName // 图片那么
           let url = ''
           // item.shareImg 是图片地址
           that.getBase64(item.shareImg, (dataURL:any) => {
             url = dataURL // 图片url转换成base64
             zip.file(fileName + '.png', url.substring(22), { base64: true })
             arrs.push(url)
             if (arrs.length === that.multipleSelections.length) { // 若要导出的图片全部转换为base64了,则开始导出
               zip.generateAsync({ type: 'blob' }).then(content => {
                 FileSaver.saveAs(content, '二维码.zip')
               })
             }
           })
         })
       }, 0)
     }
     // 图片url转换成base64
     private getBase64(url:string, callback:any) {
       var Img = new Image()
       var dataURL = ''
       Img.src = url + '?v=' + Math.random()
       Img.setAttribute('crossOrigin', 'Anonymous')
       Img.onload = function() {
         var canvas:any = document.createElement('canvas')
         var width = Img.width
         var height = Img.height
         canvas.width = width
         canvas.height = height
         canvas.getContext('2d').drawImage(Img, 0, 0, width, height)
         dataURL = canvas.toDataURL('image/jpeg')
         return callback ? callback(dataURL) : null
       }
     }
    

     JSzip API地址:https://stuk.github.io/jszip/documentation/api_jszip/constructor.html

     

       
  • 相关阅读:
    老男孩python学习_day004知识点
    老男孩python学习_day003作业
    老男孩python学习_day003知识点
    老男孩python学习_day002知识点
    老男孩python学习_day001知识点
    老男孩python学习_day002作业
    老男孩python学习_day001作业
    Struts2+Spring4+Hibernate4整合超详细教程
    解决 Ubuntu15.04 登陆界面无限循环 的问题
    jsp之间url传值出现中文乱码
  • 原文地址:https://www.cnblogs.com/hhw3/p/15425021.html
Copyright © 2011-2022 走看看