YHJ木易
YHJ木易
  • 发布:2020-04-23 09:55
  • 更新:2021-07-06 18:02
  • 阅读:3909

图片压缩及转换base64

分类:uni-app

本教程适合APP,利用5+进行图片压缩,然后转换成base64格式文件。

uni.chooseImage({  
    sizeType: ['original'],  
    sourceType: ['camera'],  
    count: 1,  
    success: async (res) => {  
            // 加载框  
            uni.showLoading({  
                title: '图片压缩中。。。'  
            });  
            let path = res.tempFilePaths[0];  
            // 压缩图片  
            plus.zip.compressImage({    
                src:path,    
                dst:path,    
                overwrite:true,    
                quality:20,    
                width: '780px',      
                height:'1040px',      
                format: 'jpg'    
                },    
                function(res) {    
                    console.log("图片压缩完成");    
                    let imgPathUrl = res.target;   
                    let imgPathSize = res.size;  
                    console.log("图片链接:"+imgPathUrl)  
                    console.log("图片尺寸:"+imgPathSize)  
                    // 文件系统中的读取文件对象,用于获取文件的内容  
                    uni.showLoading({  
                        title: '图片转换中。。。'  
                    });  
                    let reader = new plus.io.FileReader();   
                    // 文件读取操作完成时的回调函数  
                    reader.onloadend = (fileData)=> {  
                        uni.hideLoading();  
                        console.log('文件读取完成!');      
                        let speech = fileData.target.result;//base64图片   
                        // 去除base64文件头  
                        let imgData = speech.replace(/^data:image\/\w+;base64,/, "");  

                    };      
                    reader.readAsDataURL(res.target);  
                },    
                function(error) {    
                    console.log("Compress error!",error);   
                    return;   

            });  
        },  
        fail:(err) => {  
            // 加载框  
            console.log(err)  
            uni.showToast({  
                icon: 'none',  
                duration:3000,  
                title: '拍照失败'  
            });  
        }  
    });
0 关注 分享

要回复文章请先登录注册

2***@qq.com

2***@qq.com

回复 能者先赏 :
dst和src路径和不能一样,修改dst路径为“_doc/a.jpg”,参考https://ask.dcloud.net.cn/article/id-12814__page-3
2021-07-06 18:02
能者先赏

能者先赏

压缩之后我本地的图片也没了0.0, 这要怎么弄呀
2020-11-06 15:43