element-ui上傳組件添加圖片壓縮功能

1、compress.js

/**
 * 圖片壓縮,默認同比例壓縮
 * @param fileObj
 * 圖片對象
 * 回調(diào)函數(shù)有一個參數(shù),base64的字符串數(shù)據(jù)
 * @param maxSize
 * 對多大的圖片進行壓縮 file.size
 * @param picQuality
 * 壓縮圖片的質(zhì)量 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; // 默認圖片質(zhì)量為0.7
          // 生成canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          // 創(chuàng)建屬性節(jié)點
          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);
          // 圖像質(zhì)量
          if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
            quality = fileObj.quality;
          }
          // quality值越小,所繪制出的圖像越模糊
          const data = canvas.toDataURL(fileObj.type, quality);
          // 壓縮完成執(zhí)行回調(diào)
          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的,壓縮質(zhì)量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;
    }
  },
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容