先压缩图片

	//先把图片进行压缩

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;
	}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐