您的位置:首页 > 移动开发 > 微信开发

小程序开发:调用百度文字识别接口实现图文识别,Node.js开发

2021-01-30 22:05 1086 查看

百度云开发注册与配置

首先需要注册百度账号,并登录百度云,进入管理控制台,创建文字识别应用,如下图

创建完应用后,打开应用管理可见APP_ID、API_KEY、SECRET_KEY,需要用在小程序端调用文字识别接口。

小程序服务端开发
由于百度提供了node.js的api,而小程序服务端云函数正是基于node的开发,在小程序开发工具云函数目录下打开终端导入文字识别api,命令:npm install baidu-aip-sdk,下载完成后,可在云函数目录看见node_modeules中‘baidu-aip-sdk’ api。

在云函数目录下新建conf.js用来存放APP_ID、API_KEY、SECRET_KEY。

然后吊用api中的通用文字识别接口,传入图片即可。

// 云函数入口文件
const cloud = require('wx-server-sdk')
let AipOcrClient = require("baidu-aip-sdk").ocr;
const args  = require("conf.js");
cloud.init();
// 云函数入口函数
exports.main = async (event, context) => {
// 设置APPID/AK/SK
let APP_ID = args.APP_ID;
let API_KEY = args.API_KEY;
let SECRET_KEY = args.SECRET_KEY;
// 新建一个对象,保存一个对象调用服务接口
let client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);
let fileID = event.fileID;
let res = await cloud.downloadFile({
fileID: fileID,
})
let image = res.fileContent.toString("base64");
// 调用通用文字识别, 图片参数为远程url图片
return client.generalBasic(image);
//console.log(result);
// .then(function (result) {
//   let result = JSON.stringify(result);
//   return result;
// })
}

小程序客户端开发

图片来源有两种途径,相册选择和相机拍摄。
xaingce(e){//相册响应函数

let tempFiles;
let tempFilePaths;
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success:res=>{
// tempFilePath可以作为img标签的src属性显示图片
tempFiles  = res.tempFiles[0].size;
tempFilePaths = res.tempFilePaths[0];
if (tempFiles > 3000000) {//大于3m
wx.showToast({
title: '图片大小大于3M',
icon: 'none',
duration: 2000
});
return;
}
wx.showLoading({
title: '识别中'
});
this.uplaodF(tempFilePaths);
setTimeout(function () {
wx.hideLoading();
}, 3000);
}
});
},
camera(){//相机响应函数
let ctx =  wx.createCameraContext();
ctx.takePhoto({
quality: "normal",
success: (res) => {
let tempFilePaths = res.tempImagePath;
this.setData({
camera: false
});
wx.showLoading({
title: '识别中'
});
this.uplaodF(tempFilePaths);
setTimeout(function () {
wx.hideLoading();
}, 3000);
}
});
},

图片上传实现代码

uplaodF(path){

let result = false;
let name = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
wx.cloud.uploadFile({
cloudPath: name,
filePath: path, // 文件路径
}).then(res => {
// get resource ID
let id = res.fileID;
//调用云函数识别图片
wx.cloud.callFunction({
name: 'tongyong',
data: {
fileID: id
}
}).then(res => {
let result = res.result.words_result;
if (result.length > 0) {
let arr = '';
for (let i = 0; i < result.length; i++) {
arr += result[i].words
}
this.setData({
words_result: arr
})
}else{
this.setData({
words_result: ''
})
}
//删除图片
wx.cloud.deleteFile({
fileList: [id]
}).then(res => {
// handle success
}).catch(error => {
// handle error
})
}).catch(err => {
console.log(err)
});

}).catch(error => {

});
},

已实现功能小程序

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: