vue2+elementui使用compressorjs压缩上传的图片

发布于:2025-07-08 ⋅ 阅读:(15) ⋅ 点赞:(0)

 首先是npm install compressorjs

然后新建一个compressorjs.js的文件

import Compressor from "compressorjs";

// 默认压缩配置
const DEFAULT_COMPRESS_OPTIONS = {
  quality: 0.6, // 默认压缩质量 (0-1)
  maxWidth: 1920, // 最大宽度
  maxHeight: 1080, // 最大高度
  convertSize: 5 * 1024 * 1024, // 超过5MB的图片转为WebP
};

/**
 * 压缩图片文件
 * @param {File} file - 待压缩的图片文件
 * @param {Object} options - 压缩配置项
 * @returns {Promise<File>} 压缩后的文件
 */
export function compressImage(file, options = {}) {
  return new Promise((resolve, reject) => {
    // 合并配置并限制最小压缩质量
    const mergedOptions = {
      ...DEFAULT_COMPRESS_OPTIONS,
      ...options,
      quality: Math.max(
        0.1,
        options.quality ?? DEFAULT_COMPRESS_OPTIONS.quality
      ),
      maxWidth: Math.min(
        options.maxWidth ?? DEFAULT_COMPRESS_OPTIONS.maxWidth,
        8192
      ),
      maxHeight: Math.min(
        options.maxHeight ?? DEFAULT_COMPRESS_OPTIONS.maxHeight,
        8192
      ),
    };

    // 执行压缩
    new Compressor(file, {
      ...mergedOptions,
      success(result) {
        if (!result) {
          return reject(new Error("Compression result is empty"));
        }
        resolve(new File([result], file.name, { type: result.type }));
      },
      error(err) {
        reject(err);
      },
    });
  });
}

 

具体的使用页面。只用在上传之前before-upload的函数中压缩就可以啦

<el-upload
  :before-upload="beforeUploadImg"
>
</el-upload>

 

import { compressImage } from "@/utils/imageCompress";

async beforeUploadImg(file) {
  const fileSize = file.size / 1024 / 1024;
  let types = ["image/jpeg", "image/jpg", "image/png", "application/pdf"];
  const isImageOrPDF = types.includes(file.type);
  if (!isImageOrPDF) {
    this.$message.error("上传图片只能是 JPG/JPEG/PNG/PDF 格式!");
    return false;
  }

  try {
    // 压缩图片(仅处理大于5MB的图片)。当前你也可以不加这个限制就是压缩所有上传的图片
    if (fileSize > 5) {
      const compressedFile = await compressImage(file, {
        quality: fileSize > 10 ? 0.7 : 1,
        axWidth: Infinity, // 不限制宽度
        maxHeight: Infinity, // 不限制高度
      });
      return compressedFile; // 返回压缩后的文件
    }
    return file;
  } catch (err) {
    if (fileSize > 5) {
      this.$message({
        message: "上传图片大小超过限制",
        type: "warning",
      });
      return false;
    }
    console.error("压缩失败:", err);
    return file; // 降级处理:上传原文件
  }

}