基于uniapp的上传图片压缩图片


该功能的本质是把用户上传的图片重新在canvas上绘制,然后降低canvas画布的画质,达到降低图片像素的目的

第一步:在页面中创建canvas画布

<!-- 压缩图片-canvas -->
		<view style="overflow: hidden;width: 0px;height: 0px;position: fixed;top: -100%;left: -100%;">
			<canvas canvas-id="compress" width="0px" height="0px"></canvas>
		</view>

调用微信小程序api上传图片

这里我们使用的是腾讯云的cos

/**
			 * 上传头像
			 * **/
			chooseImagesHandle() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						console.log('[上传头像]', res);

						this.compressImage({
							canvasId: 'compress',
							filePath: res.tempFiles[0].path,
							limitWidth: 200,
							quality: 0.5
						}).then(compressPath => {
							let filePath = compressPath;
							let timestamp = new Date().getTime();
							let filename = timestamp + '.' + filePath.substr(filePath.lastIndexOf('/') + 1).split('.')[1];
							COS.uploadFileToTencentClound('client', filename, filePath).then(res => {
								console.log("[腾讯云上传图片回调]", res)
								this.queryObject['avatar'] = res.relativepath;
								this.tempavatar = res.absolutepath;
							});
						})

					}
				});
			},

压缩图片的逻辑代码

/**
			 * 压缩图片
			 * @param {object} options 
			 * {
			 *   canvasId:'compress',
			 *   path:'',//图片的路径
			 *   limitWidth:200,//限制图片的宽度
			 *   quality:0.5,//图片的质量
			 * }
			 * **/
			compressImage(options) {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: "压缩中...",
						icon: 'none'
					})
					const canvasId = options.canvasId;
					uni.getImageInfo({
						src: options.filePath,
						success: (res) => {
							let canvasWidth, canvasHeight;
							const limitWidth = options.limitWidth;
							if (res.width > limitWidth || res.height > limitWidth) {
								if (res.width > res.height) {
									canvasWidth = limitWidth;
									canvasHeight = (limitWidth / res.width) * res.height;
								} else {
									canvasWidth = (limitWidth / res.height) * res.width;
									canvasHeight = limitWidth;
								}

							} else {
								canvasWidth = res.width;
								canvasHeight = res.height;
							}

							//创建 canvas 的绘图上下文 CanvasContext 对象
							const ctx = uni.createCanvasContext(canvasId, this);
							//清除画布
							ctx.clearRect(0, 0, canvasWidth, canvasHeight)
							ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight);
							ctx.draw(false, setTimeout(() => {
								uni.canvasToTempFilePath({
									canvasId: canvasId,
									x: 0,
									y: 0,
									width: canvasWidth,
									height: canvasHeight,
									destWidth: canvasWidth,
									destHeight: canvasHeight,
									quality: options.quality,
									success: (result) => {
										console.log("[success]", result)
										uni.hideLoading();
										resolve(result.tempFilePath);
									},
									fail: (err) => {
										console.log("[err]", err)
										uni.hideLoading();
										uni.showToast({
											title: `压缩失败`,
											icon: 'none',
										});
										resolve(options.filePath);
									}
								}, this)
							}, 300))

						}
					})
				})


			}

猜你喜欢

转载自blog.csdn.net/qq_37117408/article/details/130747742