图片压缩上传

图片压缩的方法

    // 图片压缩
    compressImage(file, success, error)  {
      // 图片小于1M不压缩
      // if (file.size < Math.pow(1024, 2)) {
      //   return success(file);
      // }
      const name = file.name; //文件名
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = e => {
        const src = e.target.result;

        const img = new Image();
        img.src = src;
        img.onload = e => {
          const w = img.width;
          const h = img.height;
          const quality = 0.8;  // 默认图片质量为0.92
          // 生成canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          // 创建属性节点
          const anw = document.createAttribute("width");
          anw.nodeValue = w;
          const anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);

          // 铺底色 PNG转JPEG时透明区域会变黑色
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, w, h);

          ctx.drawImage(img, 0, 0, w, h);
          // quality值越小,所绘制出的图像越模糊
          const base64 = canvas.toDataURL('image/jpg', quality); // 图片格式jpeg或webp可以选0-1质量区间

          // 返回base64转blob的值
          console.log(`原图${(src.length/1024).toFixed(2)}kb`, `新图${(base64.length/1024).toFixed(2)}kb`);
          // 去掉url的头,并转换为byte
          const bytes = window.atob(base64.split(',')[1]);
          // 处理异常,将ascii码小于0的转换为大于0
          const ab = new ArrayBuffer(bytes.length);
          const ia = new Uint8Array(ab);
          for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
          }
          file = new Blob([ab], {type : 'image/jpg'});
          file.name = name;

          success(file);
        }
        img.onerror = e => {
          error(e);
        }
      }
      reader.onerror = e => {
        error(e);
      }
    },

调用上传

// file.file 原来的对象  obj 压缩好的对象
      this.compressImage(file.file, obj => {
        console.log(file.file)
        console.log(obj)
        file.status = 'uploading'
        file.message = '上传中...';
        setTimeout(() => {
          let formData = new FormData()
          formData.append('file', obj, obj.name)
          ........
        },1000)
      })

第二种方法:

yarn add image-compressor.js
import ImageCompressor from 'image-compressor.js';

    afterRead(file) {
      file.status = 'uploading'
      file.message = '上传中...'
      const isLt2M = (file.file.size / 1024 / 1024) < 10
      if (!isLt2M) {
        Dialog({ message: '图片大小不能超过 10MB,请重新上传' })
        return
      }
      let that=this
      new ImageCompressor(file.file, {
        quality: .8,
        convertSize: 2000,
        success(result) {
          console.log(file.file)
          console.log(result)
          debugger
          that.formData.append('file', result, result.name)
          // this.formData.append('file', file.file, file.file.name)
          uploadFile(that.formData).then(res => {
            if (that.imgIndex === 1) {
              that.addOrderList.orderProof = res.data.data
              file.status = 'done'
            } else if (that.imgIndex === 2) {
              that.addOrderList.paymentProof = res.data.data
              file.status = 'done'
            }
          })
        }
      })
    },

Blob对象转File

let files = new window.File([blob], 'xx.jpg', {type: 'image/jpeg'})
console.log(files)
原文地址:https://www.cnblogs.com/ronle/p/12345464.html