uniapp h5上传图片压缩

有h5和小程序的判断 小程序其实可以直接用sizeType的

		  // 二分查找法压缩
		  uni.chooseImage({
		  					count: 1, //默认9
		  					sizeType:['compressed'],
		  			        success: (chooseImageRes) => {
								console.log(chooseImageRes)
		  			            const tempFilePaths = chooseImageRes.tempFilePaths;
		  			            const filePath = tempFilePaths[0];
		  			            // 获取图片文件大小
		  			            uni.getFileInfo({
		  			                filePath: filePath,
		  			                success: (fileInfo) => {
		  			                    const fileSize = fileInfo.size; // 图片文件大小,单位为B
		  			                    // 判断图片大小是否超过200KB
		  			                    if (fileSize > 200 * 1024) {
		  									#ifdef H5
		  									 //h5压缩图片
		  																		 const targetSizeKB = 200; // 设置目标文件大小,单位为KB,根据需求调整
		  that.compressH5(chooseImageRes.tempFiles[0],targetSizeKB).then(file => {
		  											console.log('file 222 = ', file)
													  uni.uploadFile({
													    url: envChange(true) + '/oss/upFile', //上传图片的后端接口
													    file: chooseImageRes.tempFiles[0],// res.tempFilePaths[0],
													    name: 'upfile',
													    success: res => {
													      const imgUrl = res.data && JSON.parse(res.data).url
													      // that.toOrderAjax(data, imgUrl)
													    }
													  })
		  											// this.uploadCompressedImage(file);
		  											}).catch(err => {
		  												console.log('catch', err)
		  									 })
		  									#endif
		  									// //#ifdef APP-PLUS || MP-WEIXIN
		  			      //                   // 如果超过200KB,进行压缩
		  			      //                   uni.compressImage({
		  			      //                       src: filePath,
		  			      //                       quality: 10, // 设置压缩质量(0-100)- 根据需求进行调整
		  			      //                       success: (compressRes) => {
		  			      //                           // 压缩成功后的逻辑
		  			      //                           this.uploadCompressedImage(compressRes.tempFilePath);
		  			      //                       },
		  			      //                       fail: (err) => {
		  			      //                           console.error('压缩图片失败:', err);
		  			      //                           uni.showToast({
		  			      //                               title: '压缩图片失败,请重试',
		  			      //                               icon: 'none'
		  			      //                           });
		  			      //                       }
		  			      //                   });
		  									// //#endif
		  			                    } else {
		  			                        // 如果未超过200KB,直接上传原图
											console.log('未超过200KB',filePath)
		  			                       // this.uploadCompressedImage(filePath);
		  			                    }
		  			                },
		  			                fail: (err) => {
		  			                    console.error('获取文件信息失败:', err);
		  			                    uni.showToast({
		  			                        title: '获取文件信息失败,请重试',
		  			                        icon: 'none'
		  			                    });
		  			                }
		  			            });
		  			        },
		  			        fail: (err) => {
		  			            console.error('选择图片失败:', err);
		  			            uni.showToast({
		  			                title: '选择图片失败,请重试',
		  			                icon: 'none'
		  			            });
		  			        }
		  			    });



	compressH5(fileItem, targetSizeKB, initialQuality = 1.0) {
	     const maxQuality = 1.0;
	     const minQuality = 0.0;
	     const tolerance = 0.01; // 根据需要调整公差
	     return new Promise((resolve, reject) => {
	         const binarySearch = (min, max) => {
	             const midQuality = (min + max) / 2;
	 
	             const reader = new FileReader();
	             reader.readAsDataURL(fileItem);
	             reader.onload = function () {
	                 const img = new Image();
	                 img.src = this.result;
	                 img.onload = function () {
	                     const canvas = document.createElement('canvas');
	                     const ctx = canvas.getContext('2d');
	 
	                     canvas.width = img.width;
	                     canvas.height = img.height;
	 
	                     ctx.clearRect(0, 0, canvas.width, canvas.height);
	                     ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
	 
	                     // 使用异步的 toBlob 方法
	                     canvas.toBlob(async (blob) => {
	                         const fileSizeKB = blob.size / 1024;
	 
	                         if (Math.abs(fileSizeKB - targetSizeKB) < tolerance || max - min < tolerance) {
	                             // 当前质量足够接近目标大小,使用当前质量解析
	                             resolve(URL.createObjectURL(blob));
	                         } else if (fileSizeKB > targetSizeKB) {
	                             // 如果文件大小太大,降低质量,继续二分查找
	                             binarySearch(min, midQuality);
	                         } else {
	                             // 如果文件大小太小,增加质量,继续二分查找
	                             binarySearch(midQuality, max);
	                         }
	                     }, 'image/jpeg', midQuality);
	                 };
	             };
	             reader.onerror = function (error) {
	                 reject(error);
	             };
	         };
	 
	         // 开始二分查找
	         binarySearch(minQuality, maxQuality);
	     });
	 },

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值