若依移动端Ruoyi-App——使用helang-compress组件压缩上传图片,支持App,小程序,h5,也支持各类格式图片文件。

1. 背景

前期查找了很多图片压缩方法,但是uni.compressImage 不支持h5,而且只能压缩jpg文件,使用FileReader读取图片压缩不支持微信小程序,使用canvas.darw绘制无反应,。。。。

2. 解决办法:

使用helang-compress组件,组件支持App,小程序,h5.

此组件在插件市场下载次数4417次

3. 使用方法

(1)在 script 中引用组件

import helangCompress from '../../components/helang-compress/helang-compress';

export default {
    components: {
        helangCompress
    }
}

(2)在 template 中添加组件

<helang-compress ref="helangCompress"></helang-compress>

(3)源码示例:

// 示例代码较多,请大家下载 【示例项目ZIP】进行阅读

// 单张压缩
this.$refs.helangCompress.compress({
    src:this.paths[0],
    maxSize:800,
    fileType:'jpg',
    quality:0.85,
    minSize:640 //最小压缩尺寸,图片尺寸小于该时值不压缩,非H5平台有效。若需要忽略该设置,可设置为一个极小的值,比如负数。
}).then((res)=>{
    // 压缩成功回调
}).catch((err)=>{
    // 压缩失败回调
})

// 批量压缩
this.$refs.helangCompress.batchCompress({
    batchSrc:this.paths,
    maxSize:800,
    fileType:'jpg',
    quality:0.85,
    progress:(res)=>{
        console.log('压缩进度');
        console.log(res);
    }
}).then((res)=>{
    // 压缩成功回调
}).catch((err)=>{
    // 压缩成功回调
})

 4. 本文使用方法

		<u-form-item label="选择照片" :required="true" prop="problemPhotos" borderBottom labelWidth="80" ref="item3">				
	      	<uni-file-picker
			     :source-type="sourceType"
				 :sizeType="sizeType"
		          v-model="fileList1" 
		          mode="grid" 
		          @select="select" 
		          @progress="progress" 
		          @success="success" 
		          @delete ="deletephoto" 
		          @fail="fail"
		       ref="upload"
		       limit="9"
		      >
		     </uni-file-picker>
		</u-form-item>
	// // 选择上传触发函数
			 async   select(e) {
				 	             let that = this;
			    // 根据所选图片的个数,多次调用上传函数

			     let promises=[]
				 
			     for (let i = 0; i < e.tempFilePaths.length; i++) {
						let url=e.tempFilePaths[i]
					 let imgtemp=e.tempFiles[i].file
				const fileSize = imgtemp.size
				 console.log(fileSize)
				 console.log('压缩前文件' + url + '===大小'+fileSize)
				 
             //使用helangCompress组件压缩图片 
				that.$refs.helangCompress.compress({
					src: url,
					maxSize: this.compressParams.maxSize,
					fileType: this.compressParams.fileType,
					quality: this.compressParams.quality,
					minSize: this.compressParams.minSize
				}).then((res) => {
					console.log("helangCompress压缩成功")
					console.log(res)
					this.compressUrl=res;
					const promise =this.uploadFiles(this.compressUrl)
					 promises.push(promise)
				
				}).catch((err) => {
					uni.hideLoading();
					uni.showToast({
						title: "压缩失败",
						icon: "none"
					})
				})
					
				  }
			       Promise.all(promises).then(()=>{
			      })
			   },

		

猜你喜欢

转载自blog.csdn.net/zhaolulu916/article/details/130553867