压缩图片上传,如何在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;
……
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具