zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

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

2023-02-18 16:41:46 时间

需求

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

原理

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

实现

    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