TypechoJoeTheme

香草物语

统计
登录
用户名
密码
/
注册
用户名
邮箱
输入密码
确认密码

uniapp组件uni-file-picker中对上传的图片进行压缩

Laughing博主
2024-07-29
/
0 评论
/
297 阅读
/
507 个字
/
百度已收录
07/29
本文最后更新于2024年07月29日,已超过45天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

在平时开发时,不管是前端、后端或者小程序端,为了节省带宽及存储空间,我们一般都会对上传的图片进行压缩。本文我们介绍一下使用uniapp开发小程序时,基于uni-file-picker组件进行图片压缩的方法。

开启uni-file-picker自带的压缩配置

uni-file-picker 组件通过配置 sizeType可以开启自带的压缩功能。

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

'original'代表原始文件
'compressed'代表启用压缩。
使用也比较简单,配置一下就行了。

<uni-file-picker  return-type="object" fileMediatype="image" mode="grid" :sizeType="sizeType" :auto-upload="false" 
@select="selectImage" @delete="deleteImage"/>

通过以上设置,便可实现对图片进行压缩,一般能够实现对半压缩的,比如10M的图片压缩成5M左右这样的。当然这个不是绝对的,只是个约莫的压缩率。
如果需要测试,需要使用手机进行真机调试,才可以看出来文件压缩后的大小。

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

自定义图片压缩

uni-file-picker自带的压缩功能不能满足我们需要时,我们可以自己对图片进行压缩,自定义压缩图片时,我们可以指定压缩率或循环压缩到指定大小。当然,也需要注意压缩后的图片质量。

一、创建公共压缩方法

创建公共方法imageCompress,传入file进行压缩。

// 图片压缩递归,小于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))
                    }
                })
            }
        })
        
    })
    
}

二、修改uni-file-picker上传方法

uni-file-picker上传方法时,先调用公共方法imageCompress进行压缩,压缩完成后在进行上传。

import { imageCompress } from "@/utils/leeframe.js" 
import { uploadImageCommon } from "@/common/api.js"
export default {
    data() {
        return{
            sizeType:['compressed'], //设置图片压缩
        }
    },
    onLoad(option) {
        this.workId = option.workId
    },
    methods:{
        //选择照片
        selectImage(e){
            this.timeSeting()
            if(e.tempFilePaths&&e.tempFiles){
                this.file = e.tempFiles[0].file
                this.type = 'mentou'
                this.uploadImage()    
            }
        },
 
        // 删除照片
        deleteImage(e){
            this.mentouValue = {}
        },
 
        // 上传照片
        async uploadImage(){
            // 压缩图片
            this.file = await imageCompress(this.file)
            // 要传的参数
            let params = {
                file:this.file
            }
            // 上传图片到相依的接口
            uni.uploadFile({
                url: uploadImageCommon, //后台上传地址
                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('token')
                },
                success: uploadFileRes => {
                    let imageName = JSON.parse(uploadFileRes.data).data
                    // 这里可以对返回的参数进行处理了
                    uni.showToast({ title: '上传成功', icon: "success" });
                },
                fail(err) {
                    uni.showToast({ title: '上传失败', icon: "error" });
                }
            })                
        },
        
    }
}
微信小程序UniApp
朗读
赞(0)
赞赏
感谢您的支持,我会继续努力哒!
版权属于:

香草物语

本文链接:

https://www.xiangcaowuyu.net/wechat/uniapp-component-uni-file-picker-compresses-uploaded-images.html(转载时请注明本文出处及文章链接)

评论 (0)