前言
最近在研究微信小程序,給我的感覺就是很容易上手,我自己無聊弄了一個
接下來講講這個看圖識字的功能
准備工作
我用的是百度ocr接口,識別圖片中的文字 ,先創建應用獲取key
https://console.bce.baidu.com/ai/?_=1600762881058&fromai=1#/ai/kg/app/create
API Key 和 Secret Key后面會用到
項目
目錄結構
里面用到了雲函數、雲數據庫、還有微信限制了每個包最大只能上傳2M,所以我做了分包的功能
功能界面
哈哈,界面簡陋了點
代碼
upload: function() { var that = this; wx.showActionSheet({ itemList: ['從相冊中選擇', '拍照'], itemColor: "#a3a2a2", success: function(res) { if (!res.cancel) { if (res.tapIndex == 0) { that.chooseWxImage('album') } else if (res.tapIndex == 1) { that.chooseWxImage('camera') } } } }) },
chooseWxImage: function(type) { var that = this; that.setData({ loadingHide : false }) wx.chooseImage({ sizeType: ['original', 'compressed'], sourceType: [type], success: function(res) { var tempFilesSize = res.tempFiles[0].size; if(tempFilesSize > 1024*1024*2){ that.setData({ loadingHide : true }) wx.showToast({ title: '圖片大小超出2M', icon: 'none' }) return; } console.log(res); wx.getFileSystemManager().readFile({ filePath: res.tempFilePaths[0], // 選擇圖片返回的相對路徑 encoding: 'base64', // 編碼格式 success: res => { // 成功的回調 that.request(res.data); },fail(_res){ that.setData({ loadingHide : false }) console.log(_res) } }) } }) },
這里圖片返回的base64格式,待會傳參調用百度的接口比較好,不容易出錯
識別文字接口
百度的技術文檔:https://cloud.baidu.com/doc/OCR/s/Ck3h7y2ia
這里的access_token可以通過上面的我們申請的 API Key 和 Secret Key 獲取
獲取方法:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
//識別文字 request: function(imageBade) { var that = this; var data = { access_token : access_token , image : imageBade, language_type : "CHN_ENG" } var header = {"content-type": "application/x-www-form-urlencoded"} http.request( url, 'POST', data, header, function( res ) { console.log(res.words_result); if(res.words_result.length == 0){ wx.showToast({ title: '該圖片沒有文字', icon: 'none', }); }else{ that.setData({ loadingHide : true, "textContent" : res.words_result }) } }, function( res ) { console.log( res ) wx.showToast({ title: '識別失敗', icon: 'none', }); }) }
最后
小程序體驗
公眾號
關注公眾號,回復 "看圖識字 " 可獲取源碼