uniapp图片转base64 -- 兼容微信小程序真机

直接上代码了,网上也很多一样的,这里记录下,因为仅仅第二种在真机微信小程序上我这里测试转换失败,所以就一并写在这里了:

注意:fail里面那句代码是自己封装的提示,请自行忽略

            //图片转base64
            urlTobase64(url){
                // #ifdef MP-WEIXIN
                    uni.getFileSystemManager().readFile({
                        filePath: url, //选择图片返回的相对路径
                        encoding: 'base64', //编码格式
                        success: res => { //成功的回调
                        console.log(res);
                            let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符,在页面无法显示的哦
                            _self.cropFilePath = base64;
                        },fail: (e) => {
                            _self.$uniApi.tipMsg("图片转换失败");
                        }
                    })
                // #endif
                
                // #ifndef MP-WEIXIN
                    uni.request({
                        url: url,
                        method:'GET',
                        responseType:'arraybuffer',
                        success: ress => {
                            let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64 
                            base64 = 'data:image/jpeg;base64,' + base64 //不加上这串字符,在页面无法显示的哦
                            _self.cropFilePath = base64;
                        },fail: (e) => {
                            _self.$uniApi.tipMsg("图片转换失败");
                        }
                    })
                // #endif

            }

 

猜你喜欢

转载自www.cnblogs.com/nanyang520/p/12668065.html