压缩图片lrz的使用

1,163 阅读1分钟

安装lrz依赖 npm install lrz --save-dev import lrz from "lrz";

官方方法

      lrz(fileData, { width: this.size, fieldName: "file" })
        .then(function(rst) {
          // 处理成功会执行   rst就是压缩的base64
          callback(rst);
        })
        .catch(function(err) {
          // 处理失败会执行
          console.log("压缩失败了", err);
        })
        .always(function() {
          // 不管是成功失败,都会执行
          console.log("压缩成功");
        });
    }
————————————————
版权声明:本文为CSDN博主「want、」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/javaScript_want/article/details/103477684

我在项目中使用

//上传图片此处是用在回复工单处
    getFile(file, fileList) {
      console.log(file.raw);
      console.log(fileList);
      var img = file.raw
      let imgUrl = []
      let fileType = [".png", ".PNG", ".jpg",".JPG"];
      let { name, size } = file;
      let hzIndex = name.lastIndexOf(".");
      let nameLen = name.length;
      let after =" ";//压缩后大小
      //获取后缀名
      let hz = name.substring(hzIndex, nameLen);
      let imgSize = parseFloat(size) / 1024 / 1024 > 0.2;
      if (fileList.length >= 3) {
        this.isMax = true;
      }
      if(!fileType.includes(hz)){
        Toast('请上传JPG或PNG文件');
        return 
      }else
      //图片大于200kb
      if(imgSize){
        console.log('图片大于200kb,转换');
      imgUrl = URL.createObjectURL(img, { quality: 0});
      lrz(imgUrl,{quality:0.2}).then(rst => {
        // 压缩后文件大小
         after = (rst.fileLen / 1024 / 1024).toFixed(2);//转换后大小
         let afterimg = rst.base64 //转换后base64
         console.log(after);
         if( after > 0.2){
        console.log(after);
        Toast(`请上传小于200kb的图片此图片${after}MB`);
        return}
        else{
        // 图片压缩至200kb以下转获取图片
        console.log('图片已压缩至200kb以下');
        console.log(afterimg)
        this.hideUpload = fileList.length >= 3;
        let picItem = afterimg.substring(22);
         this.ItemPicList.push(picItem);
          console.log("push");
          console.log(picItem,45454545454545454545);
          console.log(this.ItemPicList);   
      }
      });}
      else{
        // 图片小于200kb直接转获取图片
        this.hideUpload = fileList.length >= 3;
        this.getBase64(file.raw).then((res) => {
          let picItem = res.substring(22);
          this.ItemPicList.push(picItem);
          console.log("push");
          console.log(picItem);
          console.log(this.ItemPicList);
        });
      }
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
  },