微信小程序图片转base64

PS: 只支持拍照或本地图片,不支持网络路径的图片。

实现思路:使用 wx.chooseImage API 获取到图片路径,再用wx.getFileSystemManager().readFile API 读取图片的base64文件内容。

话不多说,直接上代码

chooseImage() {
      //拍照或从相册选图
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],   //所选的图片的尺寸
            sourceType: ['album', 'camera'],        //选择图片的来源
            success: res => this.urlTobase64(res.tempFilePaths[0])  //成功的回调,文件路径
        })
    },

    urlTobase64(imgPath) {
        //读取图片的base64文件内容
        wx.getFileSystemManager().readFile({
            filePath: imgPath, //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: res => console.log('data:image/png;base64,' + res.data)  //成功的回调
        })
    },

从本地相册选择图片或使用相机拍照 api文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html。
读取本地文件内容 api文档: https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readFile.html。

你可能感兴趣的:(微信小程序图片转base64)