移动拍照上传图片实现图片压缩
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
相关文章
- React源码中的计算流程和优先级
- Zabbix面试题,附详细答案!
- 前端工程师leetcode算法面试之二叉树深度广度遍历
- 谈谈前端性能优化--面试版
- 前端二面常考面试题(必备)
- 前端面试什么样的回答
- 前端必会react面试题及答案
- react面试题合集
- 技术实践丨体验量子神经网络在自然语言处理中的应用
- 如何解决回归任务数据不均衡的问题?
- 应对全场景AI框架部署挑战,MindSpore“四招”让你躺平
- 教你三种jQuery框架实现元素显示及隐藏动画方式
- 一文你带快速认识Vue-Router路由
- AI如何提升10倍筛药效率?6月18日华为云携手中科院上海药物所揭开谜底
- 我的编辑器能玩贪吃蛇,一起玩不?
- 教你在Kubernetes中快速部署ES集群
- 毕昇 JDK:为啥是ARM 上超好用的 JDK
- 带你剖析鸿蒙轻内核任务栈的源代码
- 一文教会你认识Vuex状态机
- 解读8大场景下Kunpeng BoostKit 使能套件的最佳能力和实践