图片压缩上传

function dataURLToBlob(dataurl) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

export default function compressImage(file, quality, callback) {
  // 压缩图片需要的一些元素和对象
  const reader = new FileReader();
  const img = new Image();

  return new Promise((resolve, reject) => {
    // 文件base64化,以便获知图片原始尺寸
    reader.onload = (e) => {
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);

    // 缩放图片需要的canvas
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');

    // base64地址图片加载完毕后
    img.onload = (e) => {
      const that = e.target;
      // 图片原始尺寸
      const originWidth = that.width;
      const originHeight = that.height;
      // 最大尺寸限制
      const maxWidth = 750;
      const maxHeight = 750;
      // 目标尺寸
      let targetWidth = originWidth;
      let targetHeight = originHeight;
      // 图片尺寸超过400x400的限制
      if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
          // 更宽,按照宽度限定尺寸
          targetWidth = maxWidth;
          targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        } else {
          targetHeight = maxHeight;
          targetWidth = Math.round(maxHeight * (originWidth / originHeight));
        }
      }

      // canvas对图片进行缩放
      canvas.width = targetWidth;
      canvas.height = targetHeight;
      // 清除画布
      context.clearRect(0, 0, targetWidth, targetHeight);
      // 图片压缩
      context.drawImage(img, 0, 0, targetWidth, targetHeight);
      // canvas转为blob并上传
      const dataUrl = canvas.toDataURL(file.type || 'image/png', quality);
      const blob = dataURLToBlob(dataUrl);
      resolve({
        dataUrl,
        blob,
      });
    };
  });
}

猜你喜欢

转载自blog.csdn.net/weixin_32586797/article/details/82497566