uniapp base64图片压缩/file转base64后压缩

原地址:https://blog.csdn.net/qq_40796623/article/details/122391991

 在原地址代码基础上进行了部分修改

function takePhoto() {
	uni.chooseImage({
		count: 6, //默认9
		sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album'], //从相册选择
		success: function(res) {
			// 如果是file需先将file转换base64
			blobToBase64(res.tempFiles[0]).then((res) => {
				console.log(res, 'res')
				let compressBase64Img = "";
				new Promise((resolve, reject) => {
					compressBase64Img = compress(res, 500, 0.9); //conpress封装的压缩方法
					resolve(compressBase64Img);
				}).then((response) => {
					// this.Upload(response); //上传图片接口
					console.log('response', response.split(',')[1]);
				});
			});
		}
	})
}
// 如果你所使用的是后端返回的base64直接使用
function takePhoto() {
	uni.chooseImage({
		count: 6, //默认9
		sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album'], //从相册选择
		success: function(res) {
	        new Promise((resolve, reject) => {
		    compressBase64Img = compress(需压缩的base64, 500, 0.1); //conpress封装的压缩方法	
		    // 如果需压缩的base64缺少data:image/png;base64,需手动补全,否则无法压缩
		    compressBase64Img = compress('data:image/png;base64,' + 需压缩的base64, 500, 0.1); //conpress封装的压缩方法
		    resolve(compressBase64Img);
	    }).then((response) => {
		    // this.Upload(response); //上传图片接口
		    console.log('response', response.split(',')[1]);
		    return response
	    });
	})
}


// file 转 base64
export async function blobToBase64(blob) {
	try {
		const base64 = await new Promise((resolve, reject) => {
			const fileReader = new FileReader();
			fileReader.onload = (e) => resolve(e.target.result);
			fileReader.onerror = () => reject(new Error("文件流异常"));
			fileReader.readAsDataURL(blob);
		});
		return base64;
	} catch (err) {
		console.error(err);
	}
}
//压缩base64图片
export async function compress(base64String, maxWidth, quality) {
	const mimeType = base64String.match(/:(.*?);/)[1];
	const image = new Image();

	const promise = new Promise(resolve => {
		image.onload = resolve;
		image.src = base64String;
	});

	await promise;

	let width = image.width;
	let height = image.height;

	if (Math.max(width, height) > maxWidth) {
		if (width > height) {
			height *= maxWidth / width;
			width = maxWidth;
		} else {
			width *= maxWidth / height;
			height = maxWidth;
		}
	}

	const canvas = document.createElement('canvas');
	canvas.width = width;
	canvas.height = height;

	const context = canvas.getContext('2d');
	context.clearRect(0, 0, width, height);
	context.drawImage(image, 0, 0, width, height);

	return canvas.toDataURL(mimeType, quality);
}

猜你喜欢

转载自blog.csdn.net/weixin_70862058/article/details/130910757