溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使用uniapp組件對(duì)上傳的圖片進(jìn)行壓縮至1兆以內(nèi)

發(fā)布時(shí)間:2022-11-15 09:08:49 來源:億速云 閱讀:548 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“怎么使用uniapp組件對(duì)上傳的圖片進(jìn)行壓縮至1兆以內(nèi)”,在日常操作中,相信很多人在怎么使用uniapp組件對(duì)上傳的圖片進(jìn)行壓縮至1兆以內(nèi)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”怎么使用uniapp組件對(duì)上傳的圖片進(jìn)行壓縮至1兆以內(nèi)”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

一、先開啟uni-file-picker組件里對(duì)于壓縮圖片的配置項(xiàng) sizeType,默認(rèn)是有兩個(gè)選項(xiàng)的:

  • original :正常

  • compressed:壓縮

這是組件源碼里顯示傳參的參考:

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

所以在調(diào)用uni-file-picker組件時(shí),就可以進(jìn)行設(shè)置,如下:

<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" 表示的是壓縮圖片的設(shè)置
data中設(shè)置sizeType的值:

export default {
    data() {
        return{
            mentouValue:{},          //圖片value值
            sizeType:['compressed'], //設(shè)置圖片壓縮
            sourceType:['camera'],   //這里設(shè)置的是只能使用照相機(jī),不能從相冊(cè)里傳照片
        }
    },
}

通過以上設(shè)置,可以實(shí)現(xiàn)對(duì)圖片進(jìn)行壓縮 一般是對(duì)半壓縮的,比如5兆壓縮成2.5兆左右這樣的。
如何進(jìn)行檢驗(yàn):本地是檢驗(yàn)不出來的,需要拿手機(jī)進(jìn)行真機(jī)調(diào)試,才可以看出來文件壓縮后的大小

如果對(duì)圖片大小沒有太大限制 ,直接這樣壓縮就可以了,但是有的項(xiàng)目會(huì)限制對(duì)圖片的大小必須小于1兆,這時(shí)候,光有這個(gè)設(shè)置,就滿足不了需求了,這時(shí)候我們可以再采取一點(diǎn)措施

二、將圖片再次進(jìn)行壓縮,壓縮至1兆以下,再傳至服務(wù)器中:

      1、先創(chuàng)建一個(gè)方法imageCompress,一般單獨(dú)放在公共函數(shù)里

// 圖片壓縮遞歸,小于1M跳出
export function  imageCompress(file){
	return new Promise((resolve, reject)=>{
		let { size,path } = file
		let type  = path.split(".")[1]
		//大于1M進(jìn)行壓縮,
		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、調(diào)用uni-file-picker組件的頁面中,調(diào)用該方法,然后再上傳圖片

import { imageCompress } from "@/utils/index.js" 
import { baseUrl } from "@/utils/request"
export default {
    data() {
        return{
            mentouValue:{},          //圖片value值
            sizeType:['compressed'], //設(shè)置圖片壓縮
            sourceType:['camera'],   //這里設(shè)置的是只能使用照相機(jī),不能從相冊(cè)里傳照片
            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)
            // 要傳的參數(shù)
			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
                    // 這里可以對(duì)返回的參數(shù)進(jìn)行處理了
					uni.showToast({ title: '上傳成功', icon: "success" });
				},
				fail(err) {
					uni.showToast({ title: '上傳失敗', icon: "error" });
				}
			})				
		},
		
    }
}

到此,關(guān)于“怎么使用uniapp組件對(duì)上傳的圖片進(jìn)行壓縮至1兆以內(nèi)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI