方法:通過官網提供的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')
}
})
}
})
}