uni-App使用百度OCR智能识别技术上传身份证,并自动识别,下面附上代码,
页面可以根据需要布局
1.首先注册百度智能云,并填写自己注册client_id以及client_secret
2.不需要的方法,函数都可以先不考虑
3.最后附上布局截图和后台PHP上传图片代码
4.样式组件使用colorUI组件样式
百度智能云地址:https://cloud.baidu.com/product/ocr_cards/idcard
百度OCR对接流程
- 根据地址请求获取access_token
- 拿着access_token上传图片,返回结果数据
<template>
<view>
<form>
<view class="cu-bar bg-white">
<view class="action">
身份证正面
</view>
</view>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
<image :src="imgList[index]" mode="aspectFill"></image>
<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="uploadImage" v-if="imgList.length<1">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
<view class="cu-bar bg-white cu-bar-border-top">
<view class="action">
身份证反面
</view>
</view>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item,index) in picList" :key="index" @tap="ViewPic" :data-url="picList[index]">
<image :src="picList[index]" mode="aspectFill"></image>
<view class="cu-tag bg-red" @tap.stop="DelPic" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="ChooseImage" v-if="picList.length<1">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
<view class="cu-form-group">
<view class="title">真实姓名</view>
<input placeholder="请输入真实姓名" v-model="cradInfo.true_name"></input>
</view>
<view class="cu-form-group">
<view class="title">证件号码</view>
<input placeholder="请输入身份证号码" v-model="cradInfo.card_number"></input>
</view>
<view class="cu-form-group">
<view class="title effective-date">有效期</view>
<picker mode="date" v-model="cradInfo.effective_date" @change="bindDateChange">
<view class="date" style="background: none;">{{cradInfo.effective_date || '请选择日期'}}</view>
</picker>
</view>
<view class="cu-form-group">
<view class="title">居住地址</view>
<input placeholder="请输入居住地址" v-model="cradInfo.home_address"></input>
</view>
<view class="save">
<button class="btn" :style="'background:' + colors" :disabled="btnLoading" :loading="btnLoading" @tap="saveUserInfo()">
提 交
</button>
</view>
</form>
<loading v-if="isShow == true"></loading>
</view>
</template>
<script>
import itemCell from "../commponent/setting/item-cell";
import moment from '@/common/moment';
import rfPickRegions from '@/components/rf-pick-regions';
import loading from "../commponent/public/loading.vue";
import indexConfig from '@/config/index.config';
var baseUrl = indexConfig.baseUrl;
import {
userInfo,
saveUserInfo,
uploadPic,
uploadImg
} from '@/api/basic.js';
export default {
data() {
return {
isShow: true,
userInfo: {},
userId: 0,
hasLogin: false,
btnLoading: false,
colors: '',
src: '',
picSrc: '',
bd_access_token: '',
imgList: [],
picList: [],
status: false,
card_back_pic: '',
card_front_pic: '',
cradInfo: {
effective_date: '',
true_name: '',
card_number: '',
home_address: '',
card_back_pic: '',
card_front_pic: ''
},
CustomBar: this.CustomBar,
modalName: null,
}
},
components: {
rfPickRegions,
loading
},
onLoad() {
setTimeout(() => {
this.setData({
isShow: false,
colors: this.themeColor.color
});
}, 500);
setTimeout(() => {
this.showModal();
}, 500);
//获取用户数据
this.initData();
this.getUserData();
if (this.cradInfo.card_front_pic) {
this.ViewImage();
}
if (this.cradInfo.card_back_pic) {
this.ViewPic();
}
this.getAccessToken();
},
onShow() {
},
methods: {
// 数据初始化
async initData() {
this.hasLogin = this.$mStore.getters.hasLogin;
if (this.hasLogin) {
this.userInfo = this.$mStore.state.userInfo;
this.userId = this.userInfo.userId;
console.log(this.userInfo);
} else {
this.isShow = false;
this.resetSectionData();
}
},
getUserData() {
this.$http.post(userInfo, {
user_id: this.userId
}).then(res => {
if (res.data.code == '200') {
console.log(res.data);
this.cradInfo.true_name = res.data.data.true_name;
this.cradInfo.home_address = res.data.data.home_address;
this.cradInfo.effective_date = res.data.data.effective_date;
this.cradInfo.card_number = res.data.data.card_number;
this.cradInfo.card_front_pic = res.data.data.card_front_pic;
this.cradInfo.card_back_pic = res.data.data.card_back_pic;
// this.imgList.push(res.data.data.card_front_pic);
if (res.data.data.card_front_pic) {
this.imgList.push(baseUrl + '/' + res.data.data.card_front_pic);
}
if (res.data.data.card_back_pic) {
this.picList.push(baseUrl + '/' + res.data.data.card_back_pic);
}
} else {
this.$mHelper.toast('获取数据失败');
}
}).catch(err => {
this.$mHelper.toast('服务异常');
});
},
showModal(e) {
setTimeout(() => {
if (this.status == true) {
this.modalName = e.currentTarget.dataset.target;
}
}, 1000);
},
hideModal(e) {
this.opacity = 0;
this.modalName = null
},
saveUserInfo() {
if (!this.cradInfo.card_front_pic) {
this.$mHelper.toast('请上传身份证正面');
return;
}
if (!this.cradInfo.card_back_pic) {
this.$mHelper.toast('请上传身份证反面');
return;
}
if (!this.cradInfo.true_name) {
this.$mHelper.toast('请输入真实姓名');
return;
}
if (!this.cradInfo.card_number) {
this.$mHelper.toast('请输入身份证号码');
return;
}
if (!this.cradInfo.effective_date) {
this.$mHelper.toast('请选择身份证有效期');
return;
}
if (!this.cradInfo.home_address) {
this.$mHelper.toast('请输入居住地址');
return;
}
this.$http.post(saveUserInfo, {
user_id: this.userId,
true_name: this.cradInfo.true_name,
card_number: this.cradInfo.card_number,
effective_date: this.cradInfo.effective_date,
home_address: this.cradInfo.home_address,
card_front_pic: this.cradInfo.card_front_pic,
card_back_pic: this.cradInfo.card_back_pic,
}).then(res => {
if (res.data.code == '200') {
this.opacity = 1;
this.$mHelper.toast('保存成功');
setTimeout(() => {
uni.navigateTo({
url: '../setting/index'
})
}, 1000);
} else {
this.$mHelper.toast('保存失败');
}
}).catch(err => {
this.$mHelper.toast('服务异常');
});
},
getAccessToken() {
uni.request({
url: 'https://aip.baidubce.com/oauth/2.0/token',
data: {
'grant_type': 'client_credentials',
'client_id': '',
'client_secret': ''
},
method: 'GET',
success(res) {
uni.setStorageSync('bd_access_token', res.data.access_token);
},
fail(e) {
uni.hideLoading()
uni.showToast({
title: '连接服务出错,请稍后再试!'
})
}
})
},
// 监听日期更改
bindDateChange(e) {
this.cradInfo.effective_date = e.target.value;
},
//文档说明
// https://ai.baidu.com/ai-doc/OCR/rk3h7xzck
uploadImage(e) { // 选取照片,进行OCR识别
this.imgList = [];
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
success: (res) => {
uni.showLoading({
title: '正在识别中...'
});
this.src = res.tempFilePaths[0]; //后面还能用到 src 暂且留着
console.log(res);
this.cradInfo.card_front_pic = res.tempFilePaths[0];
this.imgList = this.imgList.concat(res.tempFilePaths);
var token = uni.getStorageSync('bd_access_token');
var _self = this;
uni.uploadFile({
url: baseUrl + uploadImg,
filePath: this.cradInfo.card_front_pic,
name: 'file',
success: function(r) {
//打印
var con = JSON.parse(r.data);
console.log(con);
console.log(con.data.path);
_self.cradInfo.card_front_pic = con.data.path;
}
});
// 下面进行转码
wx.getFileSystemManager().readFile({
filePath: res.tempFilePaths[0], //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: (res) => { //成功回调页面
uni.request({
url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + token,
data: {
image: res.data,
id_card_side: 'front'
},
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: (res) => {
if (res.data.idcard_number_type == 1) {
this.content = res.data.words_result
uni.hideLoading(); //把正在加载中隐藏
this.cradInfo.true_name = this.content.姓名.words;
this.cradInfo.home_address = this.content.住址.words;
this.cradInfo.card_number = this.content.公民身份号码.words;
this.status = true;
} else {
uni.hideLoading(); //把正在加载中隐藏
this.$mHelper.toast('上传失败,请稍后再试!');
}
},
fail(e) {
uni.hideLoading(); //把正在加载中隐藏
this.$mHelper.toast('上传失败,请稍后再试!');
}
})
}
});
}
})
},
// 选择图片
ChooseImage(e) {
this.picList = [];
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
success: (res) => {
console.log(res);
this.picSrc = res.tempFilePaths[0]; //后面还能用到 src 暂且留着
this.cradInfo.card_back_pic = res.tempFilePaths[0];
if (this.picList.length != 0) {
this.picList = this.picList.concat(res.tempFilePaths);
console.log(11111);
} else {
//上传图片到后台服务器
var _self = this;
uni.uploadFile({
url: baseUrl + uploadImg,
filePath: this.cradInfo.card_back_pic,
name: 'file',
success: function(r) {
//打印
var con = JSON.parse(r.data);
console.log(con);
console.log(con.data.path);
_self.cradInfo.card_back_pic = con.data.path;
}
});
this.picList = res.tempFilePaths
}
}
});
},
// 图片预览
ViewImage(e) {
uni.previewImage({
urls: this.imgList,
current: e.currentTarget.dataset.url
});
},
// 删除图片
DelImg(e) {
this.imgList.splice(e.currentTarget.dataset.index, 1);
this.cradInfo.card_front_pic = '';
},
// 图片预览
ViewPic(e) {
uni.previewImage({
urls: this.picList,
current: e.currentTarget.dataset.url
});
},
// 删除图片
DelPic(e) {
this.picList.splice(e.currentTarget.dataset.index, 1);
this.cradInfo.card_back_pic = '';
},
}
}
</script>
<style>
button .cu-tag {
position: absolute;
top: 8upx;
right: 8upx;
}
button {
margin-top: 30rpx;
margin-bottom: 30rpx;
}
.button-sp-area {
margin: 0 auto;
width: 60%;
}
.mini-btn {
margin-right: 10rpx;
}
.btn-bg {
background-color: #007AFF !important;
}
button {
font-size: 32rpx;
}
.uni-content-view-left {
width: 25%;
float: left;
text-align: right;
}
.uni-content-view-right {
width: 75%;
float: left;
text-align: left;
color: #000000;
}
.save {
position: fixed;
bottom: 0;
width: 100%;
height: 120upx;
display: flex;
justify-content: center;
align-items: center;
}
.save view {
display: flex;
}
.save .btn {
box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
width: 70%;
height: 80upx;
border-radius: 80upx;
background-color: #f23a3a;
color: #fff;
justify-content: center;
align-items: center;
font-size: 30upx;
}
.save .btn .icon {
height: 80upx;
color: #fff;
font-size: 30upx;
justify-content: center;
align-items: center;
}
.date {
height: 80upx;
line-height: 80upx;
font-size: 28upx + 2upx;
color: #303133;
}
.line-h {
line-height: 80upx;
}
.cu-form-group .title {
padding-right: 100rpx;
}
.cu-form-group .effective-date {
padding-right: 130rpx !important;
}
.cu-bar-border-top {
border-top: 1rpx solid #eee;
}
</style>
PHP上传图片代码
/**
* 上传图片
*/
public function uploadImage()
{
if (!empty($_FILES['file'])) {
$dir = "Public/Uploads/Card/";
//获取扩展名
$exename = $this->getExeName($_FILES['file']['name']);
if ($exename != 'png' && $exename != 'jpg' && $exename != 'gif') {
exit('不允许的扩展名');
}
$image_name = md5(date('YmdHis') . rand(1000, 9999)) . '.' . uniqid();
$imageSavePath = $dir . $image_name . '.' . $exename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)) {
$res = array(
'path' => $imageSavePath,
'data' => $imageSavePath
);
$this->apiResponse->show(200, '获取数据成功', $res);
} else {
$this->apiResponse->show(400, '获取数据失败');
}
}
}
public function getExeName($fileName)
{
$pathinfo = pathinfo($fileName);
return strtolower($pathinfo['extension']);
}