前端实现图片压缩,限制大小和宽高

最近公司开发业务里有个需求是对上传图片进行压缩限制大小。实现限制大小的时候,采用的是二分法。

// 图片压缩大小至40kb, device为二分法压缩次数
// 这里压缩次数由图片大小去控制,可以多尝试几个数,来达到最好的压缩效果
    CompressorImage(file, size = 40, device = 10) {
      return new Promise((resolve) => {
        const reader = new FileReader() // 创建fileReader
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')
        reader.onload = ({ target: { result: src } }) => {
          const image = new Image() // 创建 img 元素
          image.onload = async () => {
            // 原始图片尺寸
            const originWidth = image.width
            const originHeight = image.height
            // 设置最大尺寸
            const maxWidth = 1000
            const maxHeight = 800
            // 设置目标尺寸
            let targetWidth = originWidth
            let targetHeight = originHeight
            // 图片尺寸超过限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽 按照宽度限定尺寸
                targetWidth = maxWidth
                targetHeight = Math.round(maxWidth * (originHeight / originWidth))
              } else {
                // 更高 按照高度限定尺寸
                targetHeight = maxHeight
                targetWidth = Math.round(maxHeight * (originWidth / originHeight))
              }
            }
            // canvas对图片进行缩放
            canvas.width = targetWidth
            canvas.height = targetHeight
            // 清除画布
            if (context) context.clearRect(0, 0, targetWidth, targetHeight)
            // 将图片划到canvas上
            if (context) context.drawImage(image, 0, 0, targetWidth, targetHeight)
            let canvasURL, miniFile
            let L = true
            let quality = 0
            const detail = []
            let start = Date.now()
            for (let i = 1; i <= device; i++) {
              canvasURL = canvas.toDataURL('image/jpeg', L ? (quality += 1 / 2 ** i) : (quality -= 1 / 2 ** i))
              const buffer = atob(canvasURL.split(',')[1])
              let length = buffer.length
              const bufferArray = new Uint8Array(new ArrayBuffer(length))
              while (length--) {
                bufferArray[length] = buffer.charCodeAt(length)
              }
              miniFile = new File([bufferArray], file.name, { type: 'image/jpeg' })
              miniFile.size / 1024 > size ? (L = false) : (L = true)
              detail.push({
                quality,
                size: miniFile.size,
                kb: Number((miniFile.size / 1024).toFixed(2)),
                time: Date.now() - start,
              })
              start = Date.now()
            }
            const targetFile = this.baseToBlob(canvasURL, file.name)
            resolve({
              targetFile,
            })
          }
          image.src = src
        }
        reader.readAsDataURL(file)
      })
    },

    baseToBlob(dataurl, fileName) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      const theBlob = new Blob([u8arr], { type: mime })
      let files = new File([theBlob], fileName, { type: 'image/jpeg' })
      theBlob.lastModifiedDate = new Date()
      theBlob.name = fileName
      return files
    },
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值