react项目吧图片进行gzip压缩
react项目吧图片进行gzip压缩 传给后端
·
先压缩图片
//先把图片进行压缩
const compressImage = (file: any) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event: any) => {
const image: any = new Image();
image.onload = () => {
const canvas = document.createElement('canvas');
const ctx: any = canvas.getContext('2d');
const maxWidth = 800;
const maxHeight = 800;
let width = image.width;
let height = image.height;
if (width > height && width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
} else if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0, width, height);
canvas.toBlob((blob) => {
// 处理压缩后的图片 Blob 对象
resolve(blob);
}, 'image/jpeg', 0.7); // 调整压缩质量(0.7 表示70%质量)
};
image.src = event.target.result;
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
};
然后转成base64格式
const convertToBase64 = (file: any) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
resolve(reader.result);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
};
把base64进行gzip压缩 用的第三方库pako
const compressData = (data: any) => {
const base64Data = data.split(',')[1]; // 从 Base64 数据中提取真实数据部分
const add = compressString(base64Data)
return add
};
function compressString (str: string) {
if (!str || str.length <= 0) {
return str;
}
const encoder = new TextEncoder();
const uint8Array = encoder.encode(str);;
const compressedData: any = gzip(uint8Array);
const compressedString = String.fromCharCode.apply(null, compressedData);
return compressedString;
}
更多推荐
已为社区贡献1条内容
所有评论(0)