图片压缩compressorjs的基本使用

87 阅读2分钟

安装

npm install compressorjs

使用

import Compressor from 'compressorjs';

//如果图片小于1M直接去上传,如果大于1M去压缩,压缩后还大于1M给提示
const beforeUpload = async file => {   
  if (file.size > 1 * 1024 * 1024) { 
    new Compressor(file, {
      quality: 0.6, //压缩质量设置
      success: async result1 => {
        console.log(result1, result1.size, '55555555555555555'); // 压缩后的图片
        // 压缩后的一般都是Blob格式 将 Blob 对象转换为 File 对象
        compressFile.value = new File([result1], file.name, { type: file.type });

        // 检查文件大小是否小于1M
        if (compressFile.value.size > 1 * 1024 * 1024) {
          // 如果文件大于1M,可以在这里处理错误,例如显示一个提示消息

          ElMessage.warning('图片大小不能超过1M'); 
          return false;
        }
        
        
        
        const fileData = new FormData();
        fileData.append('file', compressFile.value as File);
        const result = await $DictApi.fileUpload(fileData);

        if (result && result.data && result.data.data) {
          const data = result.data.data as any;
          model.value = data.filePath; 
          emit('imgChange', model.value); 
          return true;
        }
        model.value = ''; 
        emit('imgChange', model.value);
      },
      error: err => {
        console.error(err); // 压缩失败的错误信息
      }
    });
  } else {
    const fileData = new FormData();
    fileData.append('file', file);
    const result = await $DictApi.fileUpload(fileData);

    if (result && result.data && result.data.data) {
      const data = result.data.data as any;
      model.value = data.filePath; 
      emit('imgChange', model.value);
      return true;
    }
    model.value = ''; 
    emit('imgChange', model.value); 
  } 
  return false;
};

案例2

function compressImage(file) {
  console.log('压缩前', file);  
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-new
    new Compressor(file, {
      quality: 0.6,
      success: async result1 => {
        console.log('压缩后', result1);
        resolve(result1);
      },
      error: err => {
        console.error(err);
        reject(err);
      }
    });
  });
}

//处理所有dom 结构 ,看是否包含base64图片,如果有转为文件类型,判断大小后,大于1M压缩,再上传
async function replaceImgSrcWithAlt(htmlString) {
  // 创建一个DOM元素来解析HTML字符串
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, 'text/html');

  // 获取所有img标签
  const imgElements = doc.querySelectorAll('img');

  // 如果没有img标签,直接返回原始的HTML字符串
  if (imgElements.length === 0) {
    return htmlString;
  }

  const baseFlag = hasBase64Img(imgElements);
  if (baseFlag) {
    // 遍历所有img标签
    for (const imgElement of Array.from(imgElements)) {
      compressFile.value = '';
      // 获取img标签的src属性
      const src = imgElement.getAttribute('src');

      // 检查src是否为base64格式的图片
      if (src && src.startsWith('data:image')) {
        const mimeTypeMatch = src.match(/data:image\/(\w+);base64/);
        const mimeType = mimeTypeMatch ? mimeTypeMatch[1] : '';

        // 将base64格式的图片转换为Blob对象
        const base64Data = src.split(',')[1];
        const byteCharacters = atob(base64Data);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: `image/${mimeType}` });
        compressFile.value = new File([blob], 'aa', { type: `image/${mimeType}` });

        const base64Size = byteCharacters.length;
        console.log(base64Size, blob.size, compressFile.value.size, '55555555555555555555555');
        if (base64Size > 1 * 1024 * 1024) {
          // 如果base64数据大于1M,可以在这里处理错误,例如显示一个提示消息
          // console.error('图片大小超过1M限制');
          // eslint-disable-next-line no-await-in-loop
          const compress = (await compressImage(compressFile.value)) as File;
          // eslint-disable-next-line max-depth
          if (compress.size > 1 * 1024 * 1024) {
            ElMessage.warning('图片大小不能超过1M');
            imgElement.setAttribute('src', '/');
          } else {
            const formData = new FormData();
            const fileBole = new File([compress], '', { type: `image/${mimeType}` });
            formData.append('file', fileBole, 'image.png');
            // eslint-disable-next-line no-await-in-loop
            const result = await $DictApi.fileUpload(formData);
            // eslint-disable-next-line max-depth
            if (result && result.data && result.data.data) {
              const uploadedSrc = result.data.data.filePath;
              imgElement.setAttribute('src', uploadedSrc);
            }
          }
        } else {
          // 将Blob对象添加到FormData中
          const formData = new FormData();
          formData.append('file', blob, 'image.png');
          // eslint-disable-next-line no-await-in-loop
          const result = await $DictApi.fileUpload(formData);
          // eslint-disable-next-line max-depth
          if (result && result.data && result.data.data) {
            const uploadedSrc = result.data.data.filePath;
            imgElement.setAttribute('src', uploadedSrc);
          }
        }
      } else {
        const src1 = src?.replace(/(\.(jpg|jpeg|png))(.*)$/i, '\$1') || '';
        imgElement.setAttribute('src', src1);
      }
    }
    wordLoading.value = false;
    return doc.body.innerHTML;
  }

  return htmlString;
}