【base64图片大小的计算与压缩】通常我们需要限制上传图片的大小,下面的函数可以帮助我们计算出base64图片的大小,然后根据大小按需压缩
// 获取base64图片大小,返回MB数字
function calSize(base64url: string) {
let str = base64url.replace('data:image/png;
base64,', '');
const equalIndex = str.indexOf('=');
if(str.indexOf('=') > 0) {
str = str.substring(0, equalIndex);
}
const strLength = str.length;
const fileLength = strLength - (strLength / 8) * 2;
// 返回单位为MB的大小
return(fileLength / (1024 * 1024)).toFixed(2);
}// 通过canvas压缩base64图片
function dealImage(base64: any, callback: any, w: number = 1000) {
const newImage = new Image();
const quality = 0.8;
// 压缩系数0-1之间
newImage.src = https://www.it610.com/article/base64;
newImage.setAttribute("crossOrigin", 'Anonymous');
// url为外域时需要
let imgWidth;
let imgHeight;
newImage.onload = function() {
// @ts-ignore
imgWidth = this.width;
// @ts-ignore
imgHeight = this.height;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d") as any;
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w;
canvas.height = w * imgHeight / imgWidth;
} else {
canvas.height = w;
canvas.width = w * imgWidth / imgHeight;
}
} else {
canvas.width = imgWidth;
canvas.height = imgHeight;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
// @ts-ignore
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
const newBase64 = canvas.toDataURL("image/jpeg", quality);
callback(newBase64);
}
}
}
推荐阅读
- Day 91/100 JS中宏任务(setTimeout)和微任务(async await)的执行顺序的demo
- 问题集合(1)
- 2022秋招前端面试题(五)(附答案)
- 2022秋招前端面试题(三)(附答案)
- Driver.js - 开源无依赖的 web 新手交互引导工具库,功能强大、高度可定制
- 从编译的角度来学作用域!
- arguments
- 聊聊JavaScript中你不知道的知识点
- 【跟着大佬学JavaScript】之防抖