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

(编辑:jimmy 日期: 2024/11/9 浏览:2)

需求:

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

直接上代码

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('请输入身份证号码')

    }

    if(!zheng1) {

     return Toast('请上传身份证信息页')

    }

    if(!fan1) {

     return Toast('请上传身份证国徽页')

    }

    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(/:(.*".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

    }

   }

以上就是vue在图片上传的时候压缩图片的详细内容,更多关于vue 压缩图片的资料请关注其它相关文章!

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。