JS将base64图片压缩至指定大小

base64图片压缩至指定大小

  1. 在开发中,通常在上传图片时,由于各种限制,需要将上传的图片压缩到某一大小范围内才能上传。在此提供以下方法实现该需求,复制可用。
    /**
     * 压缩图片到指定大小
     * @param baseImg base64图片
     * @param maxSize 单位kb
     */
    export function compressImgBySize (baseImg, maxSize = 200) {
      return new Promise((resolve) => {
        const strLength = baseImg.length
        const fileLength = parseInt(strLength - (strLength / 8) * 2)
        let size = parseInt((fileLength / 1024).toFixed(2))
    
        if (size <= maxSize) {
          resolve(baseImg)
          return
        }
    
        const img = new Image()
        // img.src = 'data:image/jpeg;base64,' + baseImg
        img.src = baseImg
        img.onload = () => {
          const canvas = imgToCanvas(img)
          let resUrl = ''
          let quality = 0.9
          while (size > maxSize && quality > 0) {
            resUrl = canvas.toDataURL('image/jpeg', quality).replace(/^data:image\/\w+;base64,/, '')
            const resLength = resUrl.length
            const resFileLength = parseInt(resLength - (resLength / 8) * 2)
            size = parseInt((resFileLength / 1024).toFixed(2))
            quality = (quality - 0.1).toFixed(1)
          }
          resolve(resUrl)
        }
        img.onerror = () => {
          resolve(baseImg)
        }
      })
    }
    
    // 把image 转换为 canvas对象
    export function imgToCanvas (image) {
      var canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      canvas.getContext('2d').drawImage(image, 0, 0)
      return canvas
    }
    
  2. 将以上代码封装为一个js文件,这里命名为compressImg.js,放置在utils文件夹下
  3. 在需要使用图片压缩的.vue文件中引入并使用,如下
    // 注意引入路径是否正确
    import { compressImgBySize } from '@/utils/compressImg'
    
    // this.applyFile[0].content 为指定的base64格式照片
    // 1200 指将图片压缩到1200kb大小以下
    compressImgBySize(this.applyFile[0].content, 1200).then(baseImg => {
    	console.log(baseImg)
    })
    

你可能感兴趣的:(开发经验总结,javascript,前端,vue.js)