base64图片压缩并转换二进制流

2021-12-07 13:50:40 浏览数 (2)

base64 压缩

代码语言:javascript复制
function dealImage(base64, w, callback) {
  var newImage = new Image();
  var quality = 0.6;
  newImage.src = base64.url;
  newImage.setAttribute('crossOrigin', 'Anonymous');
  var imgWidth, imgHeight;
  newImage.onload = function() {
    imgWidth = this.width;
    imgHeight = this.height;
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w;
        canvas.height = (w * imgHeight) / imgWidth;
      } else {
        canvas.height = w;
        canvas.width = (w * imgWidth) / imgHeight;
      }
    } else {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
      quality = 0.6;
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    var base64 = canvas.toDataURL('image/jpeg', quality);
    callback(base64);
  };
}

转换二进制流

代码语言:javascript复制
const base64toFile = (dataurl, filename = 'file') => {
  let arr = dataurl.split(',');

  let mime = arr[0].match(/:(.*?);/)[1];

  let suffix = mime.split('/')[1];

  let bstr = atob(arr[1]);

  let n = bstr.length;

  let u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  });
};

使用

代码语言:javascript复制
 let apirul = `xxx/upload_file`;
      let filedata = new FormData();
      dealImage(files[filesIndex], 500, useImg);
      function useImg(base64) {
        filedata.append('file', base64toFile(base64));
        let request = new Request(apirul, {
          method: 'POST',
          credentials: 'include',
          body: filedata
        });
        fetch(request).then(response => {
          response.json().then(async data => {
            console.log('上传成功');
            console.log(data);
            if (data.code === 0) {
              setFilesIndex(filesIndex   1);
              setImgfileId([...imgfileId, data.data]);
            } else {
              Toast.success(data.msg, 3);
            }
          });
        });
      }

0 人点赞