Front-end download image compression package

Download the jszip file-Saver plugin

npm i jszip file-saver
Copy the code

Second, obtain the base64 data corresponding to the image

  1. Image to base64 via canvas.todataURL ()

  2. The width and height of canvas should be set to the width and height of picture to avoid incomplete picture capture or distortion

  3. Image resources have cross-domain problems. If setting crossOrigin does not work, you need to configure the resources

  getImage(url) {
            return new Promise((resolve, reject) = > {
                let img = new Image()
                img.setAttribute('crossOrigin'.'anonymous')
                img.src = url
                img.onload = () = > {
                    let canvas = document.createElement('canvas')
                    let ctx = canvas.getContext('2d')
                    canvas.width = img.width
                    canvas.height = img.height
                    ctx.drawImage(img, 0.0, canvas.width, canvas.height)
                    let pattern = ctx.createPattern(img, 'no-repeat')
                    ctx.fillStyle = pattern
                    let dataURL = canvas.toDataURL()
                    resolve(dataURL)
                }
            })
        },
Copy the code

Three, packaging,

  downImage(arr) {
            let urls = arr.map(v= > v.url)
            const zip = new JSZip()
            const promises = []
            urls.forEach(item= > {
                const promise = this.getImage(item).then(data= > {
                    let arrName = item.split('/')
                    let fileName = arrName[arrName.length - 1] // Get the file name
                   // Add files one by one
                    let imgArr = data.split(', ')
                    zip.file(fileName, imgArr[1] and {base64: true }) Generate JPG data in compressed package based on base64 data
                })
                promises.push(promise)
            })
            Promise.all(promises).then(() = > {
                zip.generateAsync({ type: 'blob' }).then(content= > {
                    // Generate a binary stream
                    FileSaver.saveAs(content, 'image.zip') // Use file-saver to save a custom file name})})},Copy the code