3. 代码实现
代码编写先是完成界面部分,然后实现HiAI接口功能,界面实现可以参考快应用开发指南,这里详细介绍一下HiAI中通用文字识别接口的实现,本示例中具体实现步骤如下:
第一步:获取图片资源uri。
第二步:调用HiAI通用文字识别接口。
(1) 获取图片资源uri有两种方式,一种是获取手机相册图片uri,另一种是通过手机相机拍照获取图片uri,实现方法如下:
//获取图片资源方法
selectMedia: function (e) {
var that = this;
//判定获取图片资源方式是拍照,调用media库中takePhoto方法
if (e === 'takePhoto') {
//判断点击的是“选择第一张图片”或者是“第二张图片”按钮
if (that.chooseWay === 'selectOneImage') {
that.takePhoto('selectOneImage');
}
else {
that.takePhoto('selectTwoImage');
}
}
//判定获取图片资源方式是从相册中选择,调用media库中pickImage方法
else if (e === 'selectImage') {
if (that.chooseWay === 'selectOneImage') {
that.selectImage('selectOneImage');
} else {
that.selectImage('selectTwoImage');
}
}
else {
that.cancel();
}
},
//拍摄照片
takePhoto: function (e) {
var that = this;
that.isShow = '';
//调用media库中takePhoto方法
media.takePhoto({
success: function (data) {
console.log(`handling success: ${data.uri}`)
//将成功回调的uri存放在oneImgUri或者twoImgUri中
if (e === 'selectOneImage') {
that.oneImgUri = data.uri;
}
else {
that.twoImgUri = data.uri;
}
that.faceCompare();
}
})
},
//从手机相册中选择图片
selectImage: function (e) {
var that = this;
that.isShow = '';
//调用media库中pickImage方法
media.pickImage({
success: function (data) {
console.log(`handling success: ${data.uri}`)
//将成功回调的uri存放在oneImgUri或者twoImgUri中
if (e === 'selectOneImage') {
that.oneImgUri = data.uri;
}
else {
that.twoImgUri = data.uri;
}
//图片资源获取到之后,调用人脸比对方法
that.faceCompare();
}
})
},
(2)调用实体识别接口
//通用文字识别
detectText: function () {
var that = this;
that.result_list = [];
ai.detectText({
//源文件的uri,仅支持本地路径。
uri: that.imageUri,
//设置文本返回粒度,可选择值0(按文本块返回),1(按文本行返回),2(按文字字符返回),传入非可选值使用默认值为1。
level: 1,
success: function (data) {
//将文字识别的结果添加到数组中,用于分析结果展示
that.result_list.push(data.value);
},
fail: function (data, code) {
that.result_list.push('errorCode: ' + errCodeList[code])
},
complete: function () {
console.log('handling complete');
}
})
}