vue上传图片压缩,移动端可用

7 篇文章 0 订阅
6 篇文章 1 订阅
// 压缩前将file转换成img对象
   readImg(file) {
       return new Promise((resolve, reject) => {
           const img = new Image()
           const reader = new FileReader()
           reader.onload = function(e) {
               img.src = e.target.result
           }
           reader.onerror = function(e) {
               reject(e)
           }
           reader.readAsDataURL(file)
           img.onload = function() {
               resolve(img)
           }
           img.onerror = function(e) {
               reject(e)
           }
       })
   },
   compressImg(img, type, mx, mh) {
       return new Promise((resolve, reject) => {
           const canvas = document.createElement('canvas')
           const context = canvas.getContext('2d')
           const { width: originWidth, height: originHeight } = img
           // 最大尺寸限制
           const maxWidth = mx
           const maxHeight = mh
           // 目标尺寸
           let targetWidth = originWidth
           let targetHeight = originHeight
           if (originWidth > maxWidth || originHeight > maxHeight) {
               if (originWidth / originHeight > 1) {
                   // 宽图片
                   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)
           // 图片绘制
           context.drawImage(img, 0, 0, targetWidth, targetHeight)
           canvas.toBlob(function(blob) {
               resolve(blob)
               console.log('压缩')
           }, type || 'image/jpeg') })
   },

上传

async afterRead(res){
   let _this = this;
   let file = res.file;
   let params = new FormData();
   if(file.size/(1024*1024)>1){   //大于1M的文件压缩
       const img = await _this.readImg(file);
       const blob = await _this.compressImg(img, file.type, 1200, 1200);
       blob.name = file.name;
       params.append("file", blob,'file_pic.jpg');
   }else {
       params.append("file", file);
   }
   upload(params).then((res)=>{   //上传接口
       if(res.code == 0){
          //上传成功
       }
   })
},
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值