首页 > 其他分享 >uniapp 图片体积太大,压缩文件

uniapp 图片体积太大,压缩文件

时间:2024-11-01 15:51:53浏览次数:2  
标签:uniapp canvas img 压缩文件 width let file 体积 height

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文件

标签:uniapp,canvas,img,压缩文件,width,let,file,体积,height
From: https://www.cnblogs.com/liziqian001/p/18520404

相关文章