elementui 与cavas实现上传图片前进行压缩(解决压缩后图片背景为黑色)

beforeUpload(file) { // 文件上传前钩子
          const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/jpg' //图片格式是否为png或jpg
          const isLt10M = file.size / 1024 / 1024 < 10 //判断图片大小是否超过10MB
          if (!isJpgOrPng) {
            this.$message.error('文件格式错误!')
          } else if(!isLt10M) {
            this.$message.error('文件过大!')
          } else {
            const _this = this
            return new Promise(resolve => {
              const reader = new FileReader()
              const image = new Image()
              image.onload = (imageEvent) => {
                const originWidth = image.width
                const originHeight = image.height
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                // 最大尺寸限制,可通过设置宽高来实现图片压缩程度
                let maxWidth = 800, maxHeight = 800
                // 目标尺寸
                let targetWidth = originWidth, targetHeight = originHeight
                // 图片尺寸超过800x800的限制
                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.width = targetWidth
                canvas.height = targetHeight
                context.clearRect(0, 0, targetWidth, targetHeight)
                image.style.background='transparent'
                context.drawImage(image, 0, 0, targetWidth, targetHeight)
                const dataUrl = canvas.toDataURL('image/png', 0.8)  //png格式图片背景不会变黑
                const blobData = _this.dataURItoBlob(dataUrl)
                resolve(blobData)
              }
              reader.onload = (e => { image.src = e.target.result; })
              reader.readAsDataURL(file)
            })
          }
          return isJpgOrPng && isLt10M
        },
        // 图片base64编码转化为blob对象方法
        dataURItoBlob (dataURI) {
            let arr = dataURI.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], {type: mime})
        },

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值