如何使用百度智能云实现我们想要的效果,需要在下面这个网址注册账号:
百度智能云-云智一体深入产业
使用文档在该网址上:
简介 - 文字识别OCR
搜索产品(例如文字识别)-> 立即使用 -> 免费领取 -> 创建应用 (跟着步骤走就好了)
创建成功后,应用列表,如下图
进入管理页面
识别身份证正面示例
身份证识别文档
根据文档需求获取Access Token(Access Token的有效期(秒为单位,有效期30天);)
注意:Access Token是有有效期的,所以需要定时或者在打开页面时就获取它(登录页也可),小编是测试功能的,所以在进入有识别的页面获取的
代码如下
<view class="idcard-img">
<view class="idcard-img-content" @click="chooseImage">
<image :src="idcardUrl ? idcardUrl : '../../static/idcard.jpg'"></image>
</view>
</view>
<Button type="primary" block color="#01C1B0" @click="pickInfomation">
<view class="idcard-btn">
<image src="../../static/icon.jpg"></image>
识别身份证人像面
</view>
</Button>
先获取Access Token
let accessToken = ref('');
// 百度云获取accessToken
const getAccessToken = () => {
// 请求
uni.request({
url: '/baiduApi/oauth/2.0/token',
data: {
grant_type: 'client_credentials',
client_id: 'xxx',
client_secret: 'xxx'
},
dataType: "JSONP",
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
success: (res: any) => {
// 将得到的res先转对象,在.点出我们想要的值
accessToken.value = JSON.parse(res.data).access_token
},
fail(err) {
}
})
}
onLoad(() => {
getAccessToken()
})
注意:这里请求的携带的三个参数:grant_type、client_id、client_secret,grant_type为client_credentials表示身份证识别,值固定直接根据官方文档赋值即可,client_id和client_secret对应的是第一章圈的两个字段,分别应用创建成功的API Key和Secret Key
上传选择图片
const idcardBase64 = ref('');
const idcardUrl = ref('');
const chooseImage = () => {
uni.chooseImage({
count: 1,
success: function (res) {
// 将图片本地路径转成base64
toBase64((res.tempFilePaths as string[])[0]).then((res) => {
// 可以进行识别别身份证操作 用到OCR百度云的接口
idcardBase64.value = res;
})
let path = (res.tempFilePaths as string[])[0];
idcardUrl.value = path;
}
});
}
// 转换为base64的函数
const toBase64 = (path: string) => {
return new Promise<string>((resolve, reject) => {
uni.request({
url: path,
responseType: 'arraybuffer',
success: (res: any) => {
resolve(uni.arrayBufferToBase64(res.data))
}
})
})
}
调用百度云的识别接口
// 调用识别身份证正面的接口
const pickInfomation = () => {
uni.showLoading({
title: '正在识别中...'
})
uni.request({
url: '/baiduApi/rest/2.0/ocr/v1/idcard',
data: {
image: idcardBase64.value, // 图片的base64路径
// access_token: accessToken.value, // Access Token
access_token: "xxx", // Access Token
id_card_side: 'front' // front身份证正面 back身份证反面
},
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: (res) => {
uni.hideLoading()
console.log('res', res.data) // 这就是调用百度云OCR接口成功返回的值
},
fail(err) {
uni.hideLoading()
}
})
}
vue3中的跨越问题
修改vite.config.js
plugins: [uni()],
server: {
proxy: {
"/baiduApi": {
target: "https://aip.baidubce.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/baiduApi/, "")
},
}
}
});