亲宝软件园·资讯

展开

vue 压缩图片 vue在图片上传的时候压缩图片

皑皑嘿 人气:0
想了解vue在图片上传的时候压缩图片的相关内容吗,皑皑嘿在本文为您仔细讲解vue 压缩图片的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:vue,图片上传,vue,压缩图片,下面大家一起来学习吧。

需求:

上传到服务器的图片太大会导致服务器承受不了,故在前端传图片的时候将图片压缩后再传到服务器

直接上代码

async getRealName(){

    let nickname = this.nickname.trim()

    let idnum = this.idnum.trim()

    let nameReg = /[\u4e00-\u9fa5]/gm

    let idnumReg = /^[a-z0-9]+$/i

    let zheng1 = document.getElementById("file1").files[0]

    let fan1 = document.getElementById("file2").files[0]

    if(nickname.length < 1) {

     return Toast('请输入姓名')

    }

    if(idnum.length < 1) {

     return Toast('请输入SFZ号码')

    }

    if(!zheng1) {

     return Toast('请上传SFZ信息页')

    }

    if(!fan1) {

     return Toast('请上传SFZ国徽页')

    }

    if(zheng1.size/1024 > 1025) {

     this.imgCompress(zheng1,{quality:0.2},'zheng')

    }else {

     this.zheng = zheng1

    }

    if(fan1.size / 1024 > 1025) {

     this.imgCompress(fan1,{quality:0.2},'fan')



    }else {

     this.fan = fan1

    }

 

    setTimeout(()=>{

     let data = new FormData()

     data.append('nickname',nickname);//添加form表单中其他数据

     data.append('idnum',idnum)

     data.append('zheng',this.zheng,zheng1.name)

     data.append("fan",this.fan,fan1.name)

     let apiauth = localStorage.getItem('apiauth')

     let config = {

      headers:{'Content-Type':'multipart/form-data'},

      herders:{apiauth:apiauth}

     }

     axios.post("http://api139.ys11.ipfsico.com/index/index/realname",data,config).then((res)=>{

      Toast(res.data.msg)

      if(res.data.code == 1) {

       this.$router.replace({path:'/msite'})

      }

     })

    },1000)

 

 

   },

   //图片压缩

   imgCompress(path,obj,statu){

    let _this = this //这里的this 是把vue的实例对象指向改变为_this

    var img = new Image();

    if(statu == 'zheng') {

     img.src = _this.avatar1;

    }else {

     img.src = _this.avatar2

    }

    img.onload = function(){

     var that = this; //这里的this 是把img的对象指向改变为that 

     // 默认按比例压缩

     var w = that.width,

      h = that.height,

      scale = w / h;

     w = obj.width || w;

     h = obj.height || (w / scale);

     var quality = 0.7; // 默认图片质量为0.7

     //生成canvas

     var canvas = document.createElement('canvas');

     var ctx = canvas.getContext('2d');

     // 创建属性节点

     var anw = document.createAttribute("width");

     anw.nodeValue = w;

     var anh = document.createAttribute("height");

     anh.nodeValue = h;

     canvas.setAttributeNode(anw);

     canvas.setAttributeNode(anh);

     ctx.drawImage(that, 0, 0, w, h);

     // 图像质量

     if(obj.quality && obj.quality <= 1 && obj.quality > 0){

      quality = obj.quality;

     }

     // quality值越小,所绘制出的图像越模糊

     var base64 = canvas.toDataURL('image/jpeg', quality);

     // 回调函数返回base64的值

     var urlFile = _this.convertBase64UrlToBlob(base64) //这个地方的处理是为了把压缩的base64转化为对象,获得压缩后图片的大小size,方便对压缩后的图片再次进行判断;

     // console.log(urlFile)

     let file = _this.blobToFile(urlFile,path.name)

     console.log(file)

     if(statu == 'zheng') {

      _this.zheng = file

     }else {

      _this.fan = file

     }

 

     if(urlFile.size/1024 > 1025){

      Toast("图片过大,请重新上传图片")

     }

 

    }

 

   },

   convertBase64UrlToBlob(urlData){

    var arr = urlData.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 Blob([u8arr], {type:mime});

   },

   blobToFile(theBlob, fileName){

 

    theBlob.lastModifiedDate = new Date();

    theBlob.name = fileName;

    return theBlob;

   },

   changeImage(e) {

    console.log(e.target.files)

    if(e.target.files[0]){

     this.ownImg = false

     var file = e.target.files[0];

     console.log(file)

     let filemaxsize = 4096

     let size = file.size / 1024

     if (size > filemaxsize){

      Toast('您上传的图片过大,请重新选择')

      this.disabled = true;

      this.formatImg = false

      return false

     }

     var name = file.name

     var fileTypes = [".jpg", ".png"];

     if(name) {

      var isNext = false;

      var fileEnd = name.substring(name.indexOf("."));

      for (var i = 0; i < fileTypes.length; i++) {

       if (fileTypes[i] == fileEnd) {

        console.log(fileTypes[i])

        isNext = true;

        this.disabled = false;

        this.formatImg = true;

        break;

       }

      }

      if (!isNext){

       Toast('暂不支持该类型图片');

       name = "";

       this.disabled = true;

       this.formatImg = false

       return false;

      }

     }

     var reader = new FileReader()

     var that = this

     var image = new Image()

     reader.readAsDataURL(file)

     reader.onload = function(e) {

      that.avatar1 = this.result

     }

    }

   },

   changeImg(event){

    var file = event.target.files[0]

    var name = file.name

    var fileTypes = [".jpg", ".png"];

    if(name) {

     var isNext = false;

     var fileEnd = name.substring(name.indexOf("."));

     for (var i = 0; i < fileTypes.length; i++) {

      if (fileTypes[i] == fileEnd) {

       console.log(fileTypes[i])

       isNext = true;

       this.disabled = false;

       this.formatImg = true;

       break;

      }

     }

     if (!isNext){

      Toast('暂不支持该类型图片');

      name = "";

      this.disabled = true;

      this.formatImg = false

      return false;

     }

    }

    var reader = new FileReader()

    var that = this

    reader.readAsDataURL(file)

    reader.onload = function(event) {

     that.avatar2 = this.result

    }

   }

加载全部内容

相关教程
猜你喜欢
用户评论