H5实现图片压缩

需求:因为图片对接的接口需要图片最大是1920*1080, 但是现在有些手机拍照的分辨率可能会超过这个限制,因此需要前端对上传的图片进行压缩。

项目使用的uni.chooseImage进行上传图片,发现uniapp有自己的压缩api uni.compressImage,一开始没仔细看,使用后发现无效,阅读文档后发现,这个api对H5无效。因此只能放弃这个用法。在这里插入图片描述
后使用官方自带的api uni.getImageInfo 获取图片信息, 然后通过新建img,对图片信息进行处理。当超过指定宽高时,对图片进行裁剪。然后通过新建Blob对象得到修改后的图片路径进行上传。如下:

		checkImg() {
    
    
			var that = this;
			uni.chooseImage({
    
    
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['camera', 'album'], //这要注意,camera掉拍照,album是打开手机相册
				success: res => {
    
    
					console.log(res);
					// 选择图片后,调用获取图片信息方法,进行处理
					that.getImageInfo(res.tempFilePaths[0]);
				}
			});
		},
		getImageInfo(src) {
    
    
			let _this = this;
			uni.getImageInfo({
    
    
				src,
				success(res) {
    
    
					console.log('压缩前', res);
					let canvasWidth = res.width; //图片原始长宽
					let canvasHeight = res.height;
					let img = new Image();
					img.src = res.path;
					let canvas = document.createElement('canvas');
					let ctx = canvas.getContext('2d');
					// 这里根据要求限制图片宽高
					if (canvasWidth >= 1920) {
    
    
						canvas.width = 1600;
					} else {
    
    
						canvas.width = canvasWidth;
					}
					if (canvasHeight >= 1080) {
    
    
						canvas.height = 900;
					} else {
    
    
						canvas.height = canvasHeight;
					}
					ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
					//toBlob()方法创造Blob对象,用以展示canvas上的图片
					canvas.toBlob(function(fileSrc) {
    
    
						let imgSrc = window.URL.createObjectURL(fileSrc);
						console.log('压缩后', imgSrc);
						// 获取压缩后的图片地址,在进行上传
						_this.upImg(imgSrc);
					});
				}
			});
		},
		upImg(img) {
    
    
			var that = this;
			uni.showLoading({
    
    
				title: '正在上传'
			});
			uni.uploadFile({
    
    
				url: '自己的上传地址',
				filePath: img,
				fileType: 'image',
				name: 'file',
				success: res => {
    
    	
					// 上传成功走自己的逻辑
				}
			});
		}

猜你喜欢

转载自blog.csdn.net/oldolder/article/details/127492683