el-upload上传的图片前按比例进行压缩

组件

<el-upload
  :before-upload="onBeforeUpload"
>

原图片宽高按比例压缩

 async onBeforeUpload(file) {
      const isJPG =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/webp";
      if (!isJPG) {
        this.$message.error("图片格式不正确!");
        return false;
      }
      
      const { width: oriWidth, height: oriHeight } = await this.getImageDimensions(
        URL.createObjectURL(file)
      );
      
      const compressFile =  new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            // 按原图80%的比例压缩,根据自己需求决定
            canvas.width = oriWidth * 0.8; // 设置压缩后图片的宽度
            canvas.height = oriHeight * 0.8; // 根据原始图片比例计算压缩后图片的高度度
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            canvas.toBlob((blob) => {
              const compressedFile = new File([blob], file.name, { type: file.type, lastModified: Date.now() });
              resolve(compressedFile);
            }, file.type);
          };
        };
      });
      
      const fileRes = await compressFile;
      
      // 压缩之后图片大mb报错
      const isLt5MB = fileRes.size / 1024 / 1024 < 5;
      if (!isLt5MB) {
        this.$message.error("上传图片大小太大!");
        return false;
      } else {
        return compressFile;
      }
    },
	// 拿到原图片宽高方法
    getImageDimensions(imageUrl) {
      return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
          const width = img.width;
          const height = img.height;
          // 解析Promise,并传递宽度和高度(如果需要的话)
          resolve({ width, height });
        };
        img.onerror = () => {
          // 处理图片加载错误
          console.error("图片加载失败");
          resolve(null); // 或者根据需要拒绝Promise
        };
        img.src = imageUrl;
      });
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值