当前位置:网站首页>Uni app Baidu cloud realizes OCR ID card recognition
Uni app Baidu cloud realizes OCR ID card recognition
2022-06-26 03:40:00 【yyxhzdm】
One 、 Baidu cloud
1. Register Baidu cloud account ( website : Baidu Intelligent Cloud console - Management Center )
2. Enter Baidu cloud and click the console -> Character recognition -> Create apps as appropriate

3. Application created successfully , Click application management

There are API Key and Secret Key, For the request access_token. Reference resources “Access Token obtain ”
The document address identified by the ID card
Two 、 Application
1. obtain Access Token(Access Token The validity of the ( Seconds per unit , The period of validity 30 God );)
Be careful :Access Token It has a validity period , So you need to get it regularly or when you open the page , I am entering the page with identification , Get it after each time
(1). Method :
// obtain Identifiable Access Token
getAccessToken: function() {
var _this = this
uni.request({
url: "https://aip.baidubce.com/oauth/2.0/token",
data: {
grant_type: "client_credentials",
client_id: " Replace with... In your management application API Key", //API Key
client_secret: " Replace with... In your management application Secret Key" //Secret Key
},
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success(res) {
_this.accessToken = res.data.access_token
console.error(" obtain Identifiable accessToken = " + JSON.stringify(_this.accessToken))
}
})
},
(2). call :
onLoad() {
var _this = this
// To obtain an ID card accessToken
_this.getAccessToken()
},

(3). Select the picture and identify the ID card

This is the identity front and back layout and click event in the layout (uploadImage Parameter passing 1: It means positive 2: It means the opposite )
Select and identify the ID card method :
// ID card picture selection
uploadImage: function(ocrtype) {
var _this = this
var cardType = ""
if (ocrtype == 1) {
cardType = "front"
} else {
cardType = "back"
}
uni.chooseImage({
count: 1, // Default 9
sizeType: ['original', 'compressed'], // You can specify whether it is original or compressed , By default, both of them have
sourceType: ['album'], // Select from the album
success(res) {
var tempImg = res.tempFilePaths[0]
console.log(" Select picture path tempImg = " + JSON.stringify(tempImg))
// turn base64
pathToBase64(res.tempFilePaths[0])
.then(base64 => {
// distinguish
uni.request({
url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' +
_this.accessToken,
data: {
id_card_side: cardType,
image: base64,
language_type: 'ENG', // Identify language types , Chinese and English are combined by default
detect_direction: true, // Detect the orientation of the image
},
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: (res) => {
console.error(" Identification information info = " + JSON.stringify(res
.data))
if (ocrtype == 1) { // The front of the ID card
var cardName = res.data.words_result. full name
if (cardName != undefined) {
_this.cardFrontParh = tempImg
_this.IDCardInfo.name = res.data.words_result
. full name .words
_this.IDCardInfo.ethnic = res.data.words_result
. nation .words
_this.IDCardInfo.address = res.data
.words_result. address .words
_this.IDCardInfo.idNumber = res.data
.words_result. Citizenship number .words
_this.IDCardInfo.birthday = res.data
.words_result. born .words
_this.IDCardInfo.gender = res.data.words_result
. Gender .words
} else {
uni.showToast({
title: " Please select the correct or clear front ID card picture ",
icon: "none",
duration: 2000
})
}
} else {
var backName = res.data.words_result. Issuing authority
if (backName != undefined) {
_this.cardBackParh = tempImg
_this.IDCardInfo.signDate = res.data
.words_result. Date of issue .words
_this.IDCardInfo.issueAuthority = res.data
.words_result. Issuing authority .words
_this.IDCardInfo.expiryDate = res.data
.words_result. Expiration date .words
} else {
uni.showToast({
title: " Please select the correct or clear reverse ID card picture ",
icon: "none",
duration: 2000
})
}
}
}
})
})
.catch(error => {
console.error("error = " + JSON.stringify(error))
})
}
})
},

(4). Picture turn base64
Turn picture to base64 file (img_transform_base64.js) Put it in /components/imgtobase64 Under the table of contents
Code :
function getLocalFilePath(path) {
if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf(
'_downloads') === 0) {
return path
}
if (path.indexOf('file://') === 0) {
return path
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path)
if (localFilePath !== path) {
return localFilePath
} else {
path = path.substr(1)
}
}
return '_www/' + path
}
function dataUrlToBase64(str) {
var array = str.split(',')
return array[array.length - 1]
}
var index = 0
function getNewFileId() {
return Date.now() + String(index++)
}
function biggerThan(v1, v2) {
var v1Array = v1.split('.')
var v2Array = v2.split('.')
var update = false
for (var index = 0; index < v2Array.length; index++) {
var diff = v1Array[index] - v2Array[index]
if (diff !== 0) {
update = diff > 0
break
}
}
return update
}
export function pathToBase64(path) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
if (typeof FileReader === 'function') {
var xhr = new XMLHttpRequest()
xhr.open('GET', path, true)
xhr.responseType = 'blob'
xhr.onload = function() {
if (this.status === 200) {
let fileReader = new FileReader()
fileReader.onload = function(e) {
resolve(e.target.result)
}
fileReader.onerror = reject
fileReader.readAsDataURL(this.response)
}
}
xhr.onerror = reject
xhr.send()
return
}
var canvas = document.createElement('canvas')
var c2x = canvas.getContext('2d')
var img = new Image
img.onload = function() {
canvas.width = img.width
canvas.height = img.height
c2x.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
canvas.height = canvas.width = 0
}
img.onerror = reject
img.src = path
return
}
if (typeof plus === 'object') {
plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
entry.file(function(file) {
var fileReader = new plus.io.FileReader()
fileReader.onload = function(data) {
resolve(data.target.result)
}
fileReader.onerror = function(error) {
reject(error)
}
fileReader.readAsDataURL(file)
}, function(error) {
reject(error)
})
}, function(error) {
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: function(res) {
resolve('data:image/png;base64,' + res.data)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
export function base64ToPath(base64) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
type: type
})))
}
var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = getNewFileId() + '.' + extName
if (typeof plus === 'object') {
var basePath = '_doc'
var dirPath = 'uniapp_temp'
var filePath = basePath + '/' + dirPath + '/' + fileName
if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime
.innerVersion)) {
plus.io.resolveLocalFileSystemURL(basePath, function(entry) {
entry.getDirectory(dirPath, {
create: true,
exclusive: false,
}, function(entry) {
entry.getFile(fileName, {
create: true,
exclusive: false,
}, function(entry) {
entry.createWriter(function(writer) {
writer.onwrite = function() {
resolve(filePath)
}
writer.onerror = reject
writer.seek(0)
writer.writeAsBinary(dataUrlToBase64(base64))
}, reject)
}, reject)
}, reject)
}, reject)
return
}
var bitmap = new plus.nativeObj.Bitmap(fileName)
bitmap.loadBase64Data(base64, function() {
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: dataUrlToBase64(base64),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
quote : stay script in
<script>
import {
pathToBase64,
base64ToPath
} from "../../components/imgtobase64/img_transform_base64.js"
</script>
Use :
pathToBase64(res.tempFilePaths[0])
.then(base64 => {
console.log(" After successful conversion base64 = " + JSON.stringify(base64 ))
}).catch(error => {
console.error("error = " + JSON.stringify(error))
})
The following is a brief introduction to the file code , The code above has

边栏推荐
- Review of the paper: unmixing based soft color segmentation for image manipulation
- Double carbon bonus + great year of infrastructure construction 𞓜 deep ploughing into the field of green intelligent equipment for water conservancy and hydropower
- Mysql database foundation
- Do you want to add a key to the applet or for sequence?
- Deletelater Usage Summary in QT
- Xgboost, lightgbm, catboost -- try to stand on the shoulders of giants
- 少儿编程对国内传统学科的推进作用
- 【论文笔记】Deep Reinforcement Learning Control of Hand-Eye Coordination with a Software Retina
- Todolist incomplete, completed
- 多媒体元素,音频、视频
猜你喜欢

Analysis of the multiple evaluation system of children's programming

MySQL增删查改(进阶)

“再谈”协议

Solve the problem that the uniapp plug-in Robin editor reports an error when setting the font color and background color

解析少儿编程的多元评价体系

TiFlash 函数下推必知必会丨十分钟成为 TiFlash Contributor

丝网印刷的种类及其应用方法

显卡、GPU、CPU、CUDA、显存、RTX/GTX及查看方式

云计算基础-0

MySQL开发环境
随机推荐
Partition, column, list
JS array array JSON de duplication
P2483-[template]k short circuit /[sdoi2010] Magic pig college [chairman tree, pile]
Solve the problem that the uniapp plug-in Robin editor reports an error when setting the font color and background color
todolist未完成,已完成
Double carbon bonus + great year of infrastructure construction 𞓜 deep ploughing into the field of green intelligent equipment for water conservancy and hydropower
Classic model – RESNET
丝网印刷的种类及其应用方法
Hardware creation principle of campus maker space
MySQL development environment
Redux thunk simple case, advantages, disadvantages and thinking
国信金太阳靠谱吗?开证券账户安全吗?
培育项目式Steam教育理念下的儿童创造力
[system architecture] - how to evaluate software architecture
Route jump: click the operation button of the list to jump to another menu page and activate the corresponding menu
路由跳转之点击列表的操作按钮,跳转至另一个菜单页面并激活相应的菜单
微信小程序开发准备工作
Inkscape如何将png图片转换为svg图片并且不失真
Kotlin quick start
Click event