1
/**
 * 压缩图片
 * base64   : 图片base64字符串
 * w        : 图片宽高最大值
 * callback : 回调函数
 * quality  : 压缩系数0-1之间, 默认0.92
 * limit    : 压缩限制字符串长度单位(KB)
 * 使用:
 * import { compressBase64 } from '@/utils'
 * compressBase64(原base64, 1000, async (base64) => {
 *    console.log(base64.length)
 * })
 */
export function compressBase64 (base64, w, callback, quality = 0.92, limit = 500) {
  let newImage = new Image()
  newImage.src = base64
  newImage.setAttribute('crossOrigin', 'Anonymous')
  let imgWidth, imgHeight
  newImage.onload = function () {
    imgWidth = this.width
    imgHeight = this.height
    let canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w
        canvas.height = w * imgHeight / imgWidth
      } else {
        canvas.height = w
        canvas.width = w * imgWidth / imgHeight
      }
    } else {
      canvas.width = imgWidth
      canvas.height = imgHeight
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
    // 压缩语句
    // let base64 = canvas.toDataURL('image/jpeg', quality)
    // 如想确保图片压缩到自己想要的尺寸,500字符长度以下,请加以下语句, quality初始值根据情况自定
    let times = 0
    while (base64.length / 1024 > limit) {
      // quality -= 0.01
      base64 = canvas.toDataURL('image/jpeg', quality)
      // 限制3次,防止死循环
      if (times >= 3) {
        console.log('compress times >= 3, break')
        break
      }
      times = times + 1
    }
    // 回调函数返回,否则无法及时拿到该值
    callback(base64)
  }
}

 

posted on 2023-02-16 16:18  1161588342  阅读(227)  评论(0编辑  收藏  举报