代码功能:用户选择图片并生成Base64编码,生成的编码小于指定的maxSize(单位为MB),可以在浏览器控制台直接运行
实现原理
- 在网页上创建一个文件输入框,让用户选择图片
- 当用户选择了一个图片时,创建一个 FileReader 对象
- 使用这个 FileReader 对象读取文件内容,并将文件内容转换为 Base64 编码
- 计算这个 Base64 编码字符串的大小,并将其转换为 MB
- 如果 Base64 编码字符串的大小没有超过限制大小,打印 Base64 编码字符串以及它的大小
- 如果 Base64 编码字符串的大小超过了设置的最大大小(在这个例子中是 1MB),就创建一个 canvas 元素,根据最大大小计算新的图像尺寸,绘制图像到 canvas 中,最后将 canvas 中的图像转换为新的 Base64 编码,,打印 Base64 编码字符串以及它的大小
额外说明:因为Base64使用6位表示一个字符,而原始数据通常是以字节(8位)为单位存储的。因此,为了计算Base64编码的大小,可以用Base64字符串长度乘以6并除以8,得到相应的字节大小。
function selectImage(maxSize) {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = event => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const base64 = e.target.result;
const base64SizeMB = (base64.length * 6) / 8 / (1024 * 1024);
if (base64SizeMB > maxSize) {
console.log(`生成的Base64大小超过限制:${base64SizeMB.toFixed(2)} MB。正在压缩...`);
const img = new Image();
img.src = base64;
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const width = img.width * (maxSize / base64SizeMB);
const height = img.height * (maxSize / base64SizeMB);
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
const compressedBase64 = canvas.toDataURL('image/jpeg');
const compressedBase64SizeMB = (compressedBase64.length * 6) / 8 / (1024 * 1024);
console.log('压缩后的Base64:', compressedBase64);
console.log(`Base64大小:${compressedBase64SizeMB.toFixed(2)} MB`);
};
} else {
console.log('Base64:', base64);
console.log(`Base64大小:${base64SizeMB.toFixed(2)} MB`);
}
};
if (file) {
reader.readAsDataURL(file);
}
};
input.click();
}
selectImage(1); // 设置最大大小为1MB