需要用户上传图片的时候,怎样只通过前端来压缩图片的大小呢?
往下看⬇️
//canvas压缩图片 参数base64,callback回调函数(由于加载图片是异步的,所以必须要用回调函数来获取base64的图片)
export function imgZip(file, callback) {
let img = document.createElement('img'); //创建图片元素
img.src = file; // 传入的base64图片格式
img.onload = function() { // 创建的图片加载完成,再去压缩图片
let originWidth = img.width;
let originHeight = img.height;
// 最大宽高
let maxWidth = 400, maxHeight = 300; // 这个也可以通过参数传入设置
// 目标尺寸
let targetWidth = originWidth, targetHeight = originHeight;
// 图片尺寸超过400*300,重新计算targetWidth,targetHeight
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画布
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(img, 0, 0, targetWidth, targetHeight);
let url = canvas.toDataURL('image/jpg'); // 获取压缩后图片的base64数据
callback(url) // 通过回调函数使用url
};
}