js压缩图片上传

1、实现,自己看代码去

// 图片压缩
// 接收三个参数:
// file:是读取的文件,需要input type="file"获取或者通过js获取
// rate:压缩比例;按照原来图片的百分比
// maxSize: 压缩后的最大文件
// rate有则使用rate,最大限制拦截,会判断rate后是否大于maxSize,如果大于,则剪切,不大于,这rate
// fileType:返回内容的类型;file即压缩后的第一个参数,blob是blob文件,base64是base64文件
// 返回:promise,第一个参数:filePress,即压缩后的fileType文件;第二个参数:base64,即源文件base64
export const imgPress = ({ file, rate = 1, maxSize = 800, fileType = 'file' }) => {
  return new Promise(resolve => {
    // new一个文件读取方法,监听文件读取
    let reader = new FileReader()
    reader.readAsDataURL(file)
    let img = new Image()
    reader.onload = function (e) {
      img.src = e.target.result
    }
    img.onload = function () {
      let canvas = document.createElement('canvas')
      let context = canvas.getContext('2d')
      // 文件大小KB
      const fileSizeKB = file.size / 1024
      // 配置rate和maxSize的关系
      if (fileSizeKB * rate > maxSize) {
        rate = Math.floor(maxSize / fileSizeKB * 10) / 10
      }
      // 缩放比例,默认0.5
      let targetW = canvas.width = this.width * rate
      let targetH = canvas.height = this.height * rate
      context.clearRect(0, 0, targetW, targetH)
      context.drawImage(img, 0, 0, targetW, targetH)
      if (fileType === 'file' || fileType === 'blob') {
        canvas.toBlob(function (blob) {
          resolve({ filePress: fileType === 'blob' ? blob : new File([blob], file.name, { type: file.type }), base64: img.src })
        })
      } else {
        resolve({ filePress: fileType === 'base64' ? canvas.toDataURL(file.type) : null, base64: img.src })
      }
    }
  })
}

压缩算法涉及canvas,计算量大了,很容易导致浏览器假死,可以参考之前的webwork去实现,实际上webwork并不是那么好用。。。所以,该代码没有使用结合webwork

猜你喜欢

转载自www.cnblogs.com/baimulan/p/12053777.html