function compressImage(file, maxWidth, maxHeight, quality, callback) {
    // 创建FileReader读取文件
    let reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = e => {
      let img = new Image();
      img.src = e.target.result;

      img.onload = () => {
        // 计算压缩后的大小
        let ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
        let width = Math.min(maxWidth, img.width * ratio);
        let height = Math.min(maxHeight, img.height * ratio);

        // 创建canvas用于重新绘制图片
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);

        // 将canvas的内容转为blob文件
        canvas.toBlob(blob => {
          callback(blob);
        }, 'image/jpeg', quality);
      };
    };

    reader.onerror = error => {
      console.error('Error: ', error);
    };
  }

  function compressImagePromise(file, maxWidth, maxHeight, quality) {
    return new Promise((resolve, reject) => {
      compressImage(file, maxWidth, maxHeight, quality, (compressedFile) => {
        if (compressedFile) {
          resolve(compressedFile);
        } else {
          reject(new Error('图片压缩失败'));
        }
      });
    });
  }

  上面代码是把file问价压缩的代码,下面是调用的代码

   调用并转换会file文件

posted on 2024-11-01 15:48  李子骞  阅读(16)  评论(0编辑  收藏  举报