vue压缩图片

upLoad(img, file,callback){
      img.onload = ()=> {
        var canvas = document.createElement('canvas')
        var context = canvas.getContext('2d')
        var originWidth = img.width
        var originHeight = img.height
        // 最大尺寸限制
        var maxWidth = 650, maxHeight = 650
        // 目标尺寸
        var targetWidth = originWidth, targetHeight = originHeight;
        // 图片尺寸超过400x400的限制
        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
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight)
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight)
        // canvas转为blob并上传
        callback(canvas.toDataURL(file.file.type),1)
        }
      }
dataURLtoFile(dataurl, filename) {
     var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
         bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
     while(n--){
         u8arr[n] = bstr.charCodeAt(n);
     }
     return new File([u8arr], filename, {type:mime});
 }
// 上传图片
    afterRead(files){
      //创建form对象
      //通过append向form对象添加数据//第一个参数字符串可以填任意命名,第二个根据对象属性来找到file
      let config = {
        headers: { //添加请求头
          "Content-Type": "multipart/form-data"
        }
      };
      const that = this
      const img = new Image()
      img.src = files.content
      this.upLoad(img, files, (val)=> {
        let params = new FormData()
        params.append("file", that.dataURLtoFile(val,files.file.name))
        axios.post(this.base.uploadimg, params,config).then(res => {
          if(res.data.code === 200){
            this.card_img = res.data.data.img_url
            this.$toast.success({
              message: '上传图片成功',
              duration: 400
            })
            this.disabled = false
          }
        }).catch(err => {
          console.log(err)
        })
      })
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值