1.新建公共方法
function  imageCompress(file){
    return new Promise((resolve, reject)=>{
        let { size,path } = file
        let type  = path.split(".")[1]
        console.log(51,size,path,type)
        //大于100kb进行压缩
        if(size <= 100*1024){
            resolve(file)
            console.log(56,file)
            return false
        } 
        uni.compressImage({
            src: path,
            quality: 80,
            width:'50%',
            height: '50%',
            success: res => {
                console.log(62,res)
                let newPath = res.tempFilePath+type
                console.log(622,newPath)
                uni.getFileInfo({
                    filePath:res.tempFilePath,
                    success:async (info)=>{
                        console.log(73,info)
                        let newFile = {...file,size:info.size,path:newPath,tempFilePath:res.tempFilePath}
                        resolve(await imageCompress(newFile))
                    }
                })
            },
            fail:err=>{
                console.log(63,err)
            }
        })    
    })
}

2.页面引入

import { imageCompress} from "@/common/commonMethods.js" 

data() {
            return {
                file:'',
            }
},

methods: { 
            //选择照片
            select(e){
                console.log(68,e)
                if(e.tempFilePaths&&e.tempFiles){
                    this.file = e.tempFiles[0].file
                    this.toUpload()
                }
            },
            // 上传照片
            async toUpload(){
                // 压缩图片
                this.file = await imageCompress(this.file)    
                uni.uploadFile({
                        url: env.Dev.baseApi + api.upload,
                        filePath: this.file.tempFilePath?this.file.tempFilePath:this.file.path,
                        name: 'file',
                        success: (res) => {
                            console.log(146,JSON.parse(res.data));
                        }
                    });
            },
        }

要点:压缩图片时,宽高一定要写,否则会出现图片越压越大的情况!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐