温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么使用uniapp组件对上传的图片进行压缩至1兆以内

发布时间:2022-11-15 09:08:49 来源:亿速云 阅读:413 作者:iii 栏目:开发技术

这篇文章主要介绍“怎么使用uniapp组件对上传的图片进行压缩至1兆以内”,在日常操作中,相信很多人在怎么使用uniapp组件对上传的图片进行压缩至1兆以内问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么使用uniapp组件对上传的图片进行压缩至1兆以内”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、先开启uni-file-picker组件里对于压缩图片的配置项 sizeType,默认是有两个选项的:

  • original :正常

  • compressed:压缩

这是组件源码里显示传参的参考:

sizeType: {
	type: Array,
	default () {
		return ['original', 'compressed']
	}
},

所以在调用uni-file-picker组件时,就可以进行设置,如下:

<uni-file-picker  v-model="mentouValue" return-type="object" 
fileMediatype="image" mode="grid" :sourceType="sourceType"
:sizeType="sizeType" :auto-upload="false"  
@select="mentouSelect" @delete="mentouDelete"/>

 :sizeType="sizeType" 表示的是压缩图片的设置
data中设置sizeType的值:

export default {
    data() {
        return{
            mentouValue:{},          //图片value值
            sizeType:['compressed'], //设置图片压缩
            sourceType:['camera'],   //这里设置的是只能使用照相机,不能从相册里传照片
        }
    },
}

通过以上设置,可以实现对图片进行压缩 一般是对半压缩的,比如5兆压缩成2.5兆左右这样的。
如何进行检验:本地是检验不出来的,需要拿手机进行真机调试,才可以看出来文件压缩后的大小

如果对图片大小没有太大限制 ,直接这样压缩就可以了,但是有的项目会限制对图片的大小必须小于1兆,这时候,光有这个设置,就满足不了需求了,这时候我们可以再采取一点措施

二、将图片再次进行压缩,压缩至1兆以下,再传至服务器中:

      1、先创建一个方法imageCompress,一般单独放在公共函数里

// 图片压缩递归,小于1M跳出
export function  imageCompress(file){
	return new Promise((resolve, reject)=>{
		let { size,path } = file
		let type  = path.split(".")[1]
		//大于1M进行压缩,
		if(size< (1024*1024)){
			resolve(file)
			return false
		}
		uni.compressImage({
			src: path,
			quality: 80,
			success: res => {
				let newPath = res.tempFilePath+type
				let newName = res.tempFilePath.split("/")[res.tempFilePath.split("/").length-1]+type
				uni.getFileInfo({
					filePath:res.tempFilePath,
					success:async (info)=>{
						let newFile = {...file,size:info.size,path:newPath,name:newName,tempFilePath:res.tempFilePath}
						resolve(await imageCompress(newFile))
					}
				})
			}
		})
		
	})
	
}

  2、调用uni-file-picker组件的页面中,调用该方法,然后再上传图片

import { imageCompress } from "@/utils/index.js" 
import { baseUrl } from "@/utils/request"
export default {
    data() {
        return{
            mentouValue:{},          //图片value值
            sizeType:['compressed'], //设置图片压缩
            sourceType:['camera'],   //这里设置的是只能使用照相机,不能从相册里传照片
            file:{},
            type:'',
            workId:''
        }
    },
    onLoad(option) {
		this.workId = option.workId
	},
    methods:{
        //选择照片
        mentouSelect(e){
			this.timeSeting()
			if(e.tempFilePaths&&e.tempFiles){
				this.file = e.tempFiles[0].file
                this.type = 'mentou'
				this.toUpload()	
			}
		},
 
        // 删除照片
		mentouDelete(e){
			this.mentouValue = {}
		},
 
        // 上传照片
        async toUpload(){
			// 压缩图片
			this.file = await imageCompress(this.file)
            // 要传的参数
			let params = {
				file:this.file,
				type: this.type,
				workId:this.workId
			}
			// 上传图片到相依的接口
			uni.uploadFile({
				url: baseUrl+'/app/uploadImage', //这里为拼接的接口地址
				filePath: this.file.tempFilePath?this.file.tempFilePath:this.file.path,
				fileType: "image",
				formData:{...params},
				name: 'file',
				header: {
					'content-type': 'multipart/form-data',
				    "Authorization": uni.getStorageSync('Authorization'),
					"refToken": uni.getStorageSync('refToken')
				},
				success: uploadFileRes => {
					let imageName = JSON.parse(uploadFileRes.data).data
                    // 这里可以对返回的参数进行处理了
					uni.showToast({ title: '上传成功', icon: "success" });
				},
				fail(err) {
					uni.showToast({ title: '上传失败', icon: "error" });
				}
			})				
		},
		
    }
}

到此,关于“怎么使用uniapp组件对上传的图片进行压缩至1兆以内”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI