压缩图片的封装

1.可以设置压缩后的图片最大宽度/高度。 限制输出最大宽/高值 (如果不设置,按照原图尺寸大小)
2.要求输出格式支持blob 和 File 文件。
3.可以设置输出图片的质量级别(假设1-10级别。级别越大,质量越高,占用存储越大,越清晰)

实现过程:
  • 首先判断 maxWidth 和 maxHeight 是否都有定义。
  • 如果图片的宽度 (width) 或者高度 (height) 超过了指定的最大值,则需要进行缩放。
  • 计算缩放比例 (ratio),使用 Math.min 函数来确定应用于宽度和高度的最小比例,以确保图片在两个维度上都适应指定的最大限制。
  • 将原始的宽度和高度乘以这个比例,从而使图片缩放到适当的大小。
  • 如果只有 maxWidth 有定义,并且图片宽度 (width) 超过了 maxWidth,则需要根据比例调整高度 (height),以确保图片不会超过指定的最大宽度。
  • 如果只有 maxHeight 有定义,并且图片高度 (height) 超过了 maxHeight,则需要根据比例调整宽度 (width),以确保图片不会超过指定的最大高度
export function compressImage(options: any) {
  const { file, photoType, quality = 10, maxWidth, maxHeight } = options;
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => {
      const canvas = document.createElement('canvas');
      let width = image.width;
      let height = image.height;
      if (maxWidth && maxHeight) {
        if (width > maxWidth || height > maxHeight) {
          const ratio = Math.min(maxWidth / width, maxHeight / height);
          console.log(ratio, 'ratio');
          width *= ratio;
          height *= ratio;
        }
      } else if (maxWidth && width > maxWidth) {
        height *= maxWidth / width;
        width = maxWidth;
      } else if (maxHeight && height > maxHeight) {
        width *= maxHeight / height;
        height = maxHeight;
      }
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      if (!ctx) {
        reject(new Error('NOT 2D canvas'));
        return;
      }
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
      canvas.toBlob(
        (blob) => {
          if (!blob) {
            reject(new Error('err blob'));
            return;
          }
          if (photoType === 'blob') {
            resolve(blob);
          } else if (photoType === 'file') {
            const compressedFile = new File([blob], file.name, { type: blob.type });
            resolve(compressedFile);
          } else {
            reject(new Error('err type'));
          }
        },
        file.type,
        quality / 10
      );
    };
 
    image.onerror = () => {
      reject(new Error('onerrr'));
    };
    image.src = URL.createObjectURL(file);
  });
}
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值