js图像压缩(base64图像压缩)

1,361 阅读1分钟

js图像压缩(base64图像压缩) ,配合上篇图片裁切使用


const dataURItoBlob = (dataURI, type) => {
  var binary = atob(dataURI.split(',')[1])
  var array = []
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)], { type: type })
}
/* 压缩base64图片 */
export function dealImage(base64) {
  return new Promise((resolve)=>{
    let newImage = new Image()
    let _this = this
    let quality = 0.8 // 压缩系数0-1之间
    var blobData
    newImage.src = base64
    // newImage.setAttribute(‘crossOrigin’, ‘Anonymous’) // url为外域时需要
    let imgWidth, imgHeight
    newImage.onload = function () {
      imgWidth = this.width
      imgHeight = this.height
      let canvas = document.createElement("canvas")
      let ctx = canvas.getContext('2d')
      canvas.width = imgWidth
      canvas.height = imgHeight
      quality = 0.8
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
      let base64 = canvas.toDataURL('image/png', quality) // 压缩语句
      blobData = dataURItoBlob(base64, 'image/png')
      do {
        if (quality > 0) {
          quality = quality - 0.1
        }
        imgWidth = imgWidth * quality
        imgHeight = imgHeight * quality
        canvas.width = imgWidth
        canvas.height = imgHeight
        ctx.clearRect(0, 0, imgWidth, imgHeight)
        ctx.drawImage(newImage, 0, 0, imgWidth, imgHeight)
        base64 = canvas.toDataURL('image/png', quality) // 压缩语句
        blobData = dataURItoBlob(base64, 'image/png')
      } while ( blobData.size > 1024 * 1024 * 4)
      if(blobData.size < 1024 * 1024 * 4){
          resolve(blobData)
      }
    }
  })
}