首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >base64图片压缩并转换二进制流

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

作者头像
我乃小神神
发布2021-12-07 13:50:40
发布2021-12-07 13:50:40
2.1K0
举报
文章被收录于专栏:前端基础前端基础

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);
            }
          });
        });
      }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档