当前位置:网站首页>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
边栏推荐
- 解析社交机器人中的技术变革
- [paper notes] supersizing self supervision: learning to grasp from 50K tries and 700 robot hours
- mysql存儲過程
- MySQL数据库基础
- Solve the problem that the input box is blocked by the pop-up keyboard under the WebView transparent status bar
- Various errors in kitti2bag installation
- Good news | congratulations on the addition of 5 new committers in Apache linkage (incubating) community
- 360 秒了解 SmartX 超融合基础设施
- 计组笔记 数据表示与运算 校验码部分
- Preparation for wechat applet development
猜你喜欢
项目部署遇到的问题-生产环境
Drag and drop
Analysis on the diversification of maker space mechanism construction
Cultivate children's creativity under the concept of project steam Education
论文回顾:Unmixing-Based Soft Color Segmentation for Image Manipulation
redux-thunk 简单案例,优缺点和思考
数字孪生智慧水务,突破海绵城市发展困境
You cannot call Glide. get() in registerComponents(), use the provided Glide instance instead
MySQL addition, deletion, query and modification (Advanced)
How Inkscape converts PNG pictures to SVG pictures without distortion
随机推荐
Run multiple main functions in the clion project
How Inkscape converts PNG pictures to SVG pictures without distortion
Question about SQL: SQL question -- SQL code for multiple account logins
An easy-to-use tablayout
Qt 中 deleteLater 使用总结
Solve the problem that the input box is blocked by the pop-up keyboard under the WebView transparent status bar
Utonmos adheres to the principle of "collection and copyright" to help the high-quality development of traditional culture
How to prepare for a moving wedding
Popupwindow utility class
【论文笔记】Supersizing Self-supervision: Learning to Grasp from 50K Tries and 700 Robot Hours
Analysis on the diversification of maker space mechanism construction
【Appium踩坑】io.appium.uiautomator2.common.exceptions.InvalidArgumentException: ‘capabilities‘ are mand
项目部署遇到的问题-生产环境
小程序或者for循序要不要加key?
开通基金账户是安全的吗?怎么申请呢
Classic model - Nin & googlenet
Classic model alexnet
个人用同花顺软件买股票安全吗?怎么炒股买股票呢
You cannot call Glide. get() in registerComponents(), use the provided Glide instance instead
Xiaomi TV's web page and jewelry's web page