UNI 项目压缩图片 转BASE64上传

本方法适用于H5和APP,其它端未测试。

首先去http://tool.hhyang.cn/doc4/custom-picture/dataURLtoBlob.html

下载 并引用custom-picture.js;

然后引用

chooseImg() {
                // #ifdef APP-PLUS
                plus.gallery.pick(res => {
                
                        this.$Ctpic.dataURLtoBlob({
                            path: res,
                            // isNet: false,
                            format: 'jpg',
                            // GetBase64: true,
                            compress: 0.5,
                        }).then(res => {
                            // plus.nativeUI.toast(res)
                            let path = res.target //绝对路径
                            if (plus.os.name == "iOS") {
                                path = plus.io.convertLocalFileSystemURL(res.target) //IOS下要转绝对路径
                            }
                            const fileReader = new plus.io.FileReader()
                            fileReader.readAsDataURL(path)
                            fileReader.onloadend = (res) => { //读取文件成功完成的回调函数
                                // console.log(res.target.result) //输出base64内容
                               let base64= res.target.result;
                                
                            }
                            fileReader.onerror = err => {
                                console.log(JSON.stringify(err))
                            }
                        });
                }, err => {
                    plus.nativeUI.toast(err)
                }, {
                    maximum: 1
                })
                // #endif
                // #ifdef H5
                uni.chooseImage({
                    count: 1,
                    complete: (res) => {
                        this.showCanvas = true;
                        this.src = res.tempFilePaths[0];
                        this.$refs.helangCompress.compress({
                            src: res.tempFilePaths[0],
                            maxSize: 1920,
                            fileType: 'jpg',
                            quality: 0.7
                        }).then((res) => {
                            // 压缩成功回调
                            // console.log(res)
                            let base64 = res;
                            
                        }).catch((err) => {
                            // 压缩失败回调
                            uni.hideLoading()
                        })
                    

                    }
                })
                // #endif
            },

 

posted @ 2020-10-29 20:42  H柷H  阅读(394)  评论(0编辑  收藏  举报