说明

通过拍照或从相册选取身份证图片,转换为 base64数据,通过 http 接口提交到身份证识别接口,例如百度身份证识别,获取返回结果

注意

需要在接口提供方平台注册应用,并获取 access_token

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var access_token = uni.getStorageSync('access_token');
var that = this;
function usecamera(tempFilePaths,that) {
return new Promise((resolve,reject)=>{
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
// sourceType: ['album'], //从相册选择
success: function (res1) {
uni.showLoading({
title: '加载中',
mask:true
});
let tempFilePaths = res1.tempFilePaths[0];
plus.io.resolveLocalFileSystemURL(tempFilePaths, function(entry) {
entry.file(function(file) {
var fileReader = new plus.io.FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function(evt) {
//console.log(evt.target.result);
let base64str = evt.target.result// 页面显示图片的src
let base64 = evt.target.result.split(",")[1];// 传递给百度识别的 base64 格式的图片文件
// 开始识别
uni.request({
url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + access_token,
method: 'POST',
data: {
image: base64,
id_card_side: 'front'// 身份证 正反面 front:身份证含照片的一面 back:身份证带国徽的一面
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: res => {
if(Object.keys(res.data.words_result).length == 0){
uni.showToast({
title: '识别失败!',
mask:true
})
return;
}
resolve(res);
},
fail:err=> {
uni.showToast({
title: '识别失败!',
mask:true
})
reject(err);
}
});
}
})
})

},

});
})
}


module.exports = {
usecamera
}

使用

1
2
3
4
5
6
7
8
9
10
11
usecamera().then(res => {
let data = {
"username": res.data.words_result.姓名.words,
"native": "",
"phone": "",
"address": res.data.words_result.住址.words,
"idnumber": res.data.words_result.公民身份号码.words,
"gender": res.data.words_result.性别.words == '女' ? '0' : '1',
"isconf": '0',
}
})