element-ui上传组件添加图片压缩功能

1、compress.js

/**
 * 图片压缩,默认同比例压缩
 * @param fileObj
 * 图片对象
 * 回调函数有一个参数,base64的字符串数据
 * @param maxSize
 * 对多大的图片进行压缩 file.size
 * @param picQuality
 * 压缩图片的质量 0~1
 * @returns {Promise}
 */
export function compress(fileObj, maxSize, picQuality) {
  return new Promise((resolve, reject) => {
    const isJPG = (
      fileObj.type === 'image/jpeg' ||
      fileObj.type === 'image/png' ||
      fileObj.type === 'image/bmp'
    );
    if (fileObj.size && ((fileObj.size / 1024 / 1024) > maxSize) && isJPG) {
      try {
        // 大于1MB的图片进行压缩
        const image = new Image();
        image.src = URL.createObjectURL(fileObj);
        image.onload = function() {
          const that = this;
          // 默认按比例压缩
          let w = that.width;
          let h = that.height;
          const scale = w / h;
          w = fileObj.width || w;
          h = fileObj.height || (w / scale);
          let quality = picQuality; // 默认图片质量为0.7
          // 生成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);
          ctx.drawImage(that, 0, 0, w, h);
          // 图像质量
          if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
            quality = fileObj.quality;
          }
          // quality值越小,所绘制出的图像越模糊
          const data = canvas.toDataURL(fileObj.type, quality);
          // 压缩完成执行回调
          const newFile = convertBase64UrlToBlob(data);
          resolve(newFile);
        };
      } catch (e) {
        this.$toastr.warning('图片压缩失败~');
        resolve(fileObj);
      }
    } else {
      resolve(fileObj);
    }
  });
}
function convertBase64UrlToBlob(urlData) {
  const bytes = window.atob(urlData.split(',')[1]); // 去掉url的头,并转换为byte
  // 处理异常,将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);
  }
  return new Blob([ab], { type: 'image/png' });
};

2、在element-ui上传组件中使用方法:

import { compress } from '@/utils/compress';
// 上传之前的钩子
beforeAvatarUpload(file) {
    this.$data.uploading = true;
    // const isImage = (file.type).includes('image');
    const isJPG = (
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/bmp'
    );
    const isLt2M = file.size / 1024 / 1024 < 50;
    /* if (!isJPG) {
      this.$message.error(`上传文件 “${file.name}” 只能是 图片类型 的格式!`);
    }*/
    if (!isLt2M) {
      this.$message.error(`上传文件 “${file.name}” 的大小不能超过 50MB!`);
    }
    this.$data.uploading = isLt2M;
    if (isLt2M) {
      if (isJPG) {
        // 压缩图片大于5MB的,压缩质量0.3
        let _size = file.size / 1024 / 1024;
        if (_size > 10) {
          return compress(file, 10, 0.3);
        } else if (_size > 5) {
          return compress(file, 5, 0.5);
        } else if (_size > 3) {
          return compress(file, 3, 0.7);
        } else if (_size > 1) {
          return compress(file, 1, 0.9);
        } else {
          return compress(file, 0.5, 1);
        }
      } else {
        return isLt2M;
      }
    } else {
      return false;
    }
  },

你可能感兴趣的:(element-ui上传组件添加图片压缩功能)