方法:通过官网提供的api实现
关键代码
const imgUrl = 'data:image/png;base64,' + wx.arrayBufferToBase64(wx.getFileSystemManager().readFileSync(tempFilePaths));
完整代码加详细解释
//此事件为点击图片按钮上传的事件
insertImage() {
const that = this
//关于API wx.chooseImage解释见官网
//https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
wx.chooseImage({
count: 1,//一次只能选择一张图片
sizeType: ['original', 'compressed'],//原图或者是压缩图
sourceType: ['album', 'camera'],//相册或者是相机现拍
success: function (res) {
const tempFilePaths = res.tempFilePaths[0];//图片文件
//划重点了,此处为关键代码,结合百度经验和官方文档得来
//https://jingyan.baidu.com/article/cb5d61055c2b36405c2fe0aa.html
//https://developers.weixin.qq.com/miniprogram/dev/api/base/wx.arrayBufferToBase64.html
//https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readFileSync.html
const imgUrl = 'data:image/png;base64,' + wx.arrayBufferToBase64(wx.getFileSystemManager().readFileSync(tempFilePaths));
//editorCtx为编辑器
//更多editor的解释见官网
//https://developers.weixin.qq.com/miniprogram/dev/api/media/editor/EditorContext.html
//https://developers.weixin.qq.com/miniprogram/dev/api/media/editor/EditorContext.insertImage.html
that.editorCtx.insertImage({
src: imgUrl,
success: function () {
console.log('insert image success')
}
})
}
})
}