前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >移动拍照上传图片实现图片压缩

移动拍照上传图片实现图片压缩

作者头像
用户6379025
发布2022-12-26 15:59:44
1.7K0
发布2022-12-26 15:59:44
举报
文章被收录于专栏:莫凡莫凡

需求

手机拍照一般手机需要5m大小的内存上传过程需要流量大,上传时间长的问题,为更好的用户体验需要对图片进行压缩。

原理

主要是利用上传到文件装为图片,将图片放到canvas中渲染,在到canvas渲染的图片导出base64

实现

代码语言:javascript
复制
    function zipImg (fileObj) {
      const maxHeight = 600;
      //最大宽度
      const maxWidth = 600;
      return new Promise((resolve, reject) => {
        let reader = new FileReader()  
        reader.readAsDataURL(fileObj);
       
        let path = "";
        reader.onload = (e) => {
          path = e.currentTarget.result;
          let img = new Image();
          img.src = path;
          img.onload = function () {
            const originHeight = img.height;
            const originWidth = img.width;
            let compressedWidth = img.height;
            let compressedHeight = img.width;
            if (originWidth > maxWidth && originHeight > maxHeight) {
              // 更宽更高,
              if (originHeight / originWidth > maxHeight / maxWidth) {
                // 更加严重的高窄型,确定最大高,压缩宽度
                compressedHeight = maxHeight;
                compressedWidth = maxHeight * (originWidth / originHeight);
              } else {
                //更加严重的矮宽型, 确定最大宽,压缩高度
                compressedWidth = maxWidth;
                compressedHeight = maxWidth * (originHeight / originWidth);
              }
            } else if (originWidth > maxWidth && originHeight <= maxHeight) {
              // 更宽,但比较矮,以maxWidth作为基准
              compressedWidth = maxWidth;
              compressedHeight = maxWidth * (originHeight / originWidth);
            } else if (originWidth <= maxWidth && originHeight > maxHeight) {
              // 比较窄,但很高,取maxHight为基准
              compressedHeight = maxHeight;
              compressedWidth = maxHeight * (originWidth / originHeight);
            } else {
              // 符合宽高限制,不做压缩
            }
            // 生成canvas
            let canvas = document.createElement("canvas");
            let context = canvas.getContext("2d");
            canvas.height = compressedHeight;
            canvas.width = compressedWidth;
            // context.globalAlpha = 0.2;
            context.clearRect(0, 0, compressedWidth, compressedHeight);
            context.drawImage(img, 0, 0, compressedWidth, compressedHeight);

            let base64 = canvas.toDataURL("image/*");
            // 通过base64转二进制
            resolve(base64);
          };
        };
      });
    },
let fileObj=document.querySelector(input).file[0];
zipImg(fileObj).then(base64=>{
  console.log(base64)
})

参考 compressUtils-demo

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-04-08,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • 原理
  • 实现
  • 参考 compressUtils-demo
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档