压缩图片封装函数

81 阅读1分钟

压缩图片封装函数

function imageCompress(fil, quality = 0.7 ) {  
  return new Promise((resolve, reject) => {  
    const image = new Image()  
    image.src = URL.createObjectURL(file)  
    image.onload = function () {  
      const that = this  
      // 默认按比例压缩  
      let w = that.width  
      let h = that.height  
      const scale = w / h  
      w = file.width || w  
      h = file.height || w / scale  
      // 生成canvas  
      const canvas = document.createElement('canvas')  
      const ctx = canvas.getContext('2d')  
      // 创建属性节点  
      const anw = document.createAttribute('width')  
      anw.nodeValue = w  
      const anh = document.createAttribute('height')  
      anh.nodeValue = h  
      canvas.setAttributeNode(anw)  
      canvas.setAttributeNode(anh)  
      ctx.drawImage(that, 0, 0, w, h)  
      // 图像质量  
      if (file.quality && file.quality <= 1 && file.quality > 0) {  
        quality = file.quality  
      }  
      // quality值越小,所绘制出的图像越模糊  
      const base64 = canvas.toDataURL(file.type, quality)  
      // 压缩完成执行回调  
      const blob = base64ToBlob(base64)  
      const newFile = new File([blob], [file.name](http://file.name/), { type: file.type })  
      resolve(newFile)  
    }  
  })  
}