压缩图片上传,如何在onload中return

背景: 很多情况下我们希望在onload事件中返回一个值,例如我们在图片加载完以后返回一些图片的信息

## 如果我们直接返回的话都知道是return不出来的
const image = new Image();
image.onload = function () {
     ...
     return ...
};
## 解决办法:
## Promise对象我们可以更简单的解决这个问题,直接就可以在then中取得我们想要的值,可以举一反三。
##在utils=>tool.js
//base64 略缩图
export function base64ThumbImage(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.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);
           let res = dataUrl.replace(
               /^data:image\/\w+;base64,/,
               ""
           );
           resolve({
               res,
           });
       };
   });
}

然后在vue文件中使用

##使用
import { base64ThumbImage } from "@/utils/tools";
## 注意传入的file参数是file格式
let that=this
 base64ThumbImage(file).then((dataUlr) => {
        that.photoBase64 = dataUlr.res;
        ……
      });
posted @ 2021-09-26 13:48  赵辉Coder  阅读(495)  评论(0编辑  收藏  举报