一、百度云
1.注册百度云账号(网址:百度智能云控制台-管理中心)
2.进入百度云点击控制台 -> 文字识别 -> 根据情况创建应用
3.创建应用成功,点击管理应用
里面有API Key和Secret Key,用于请求access_token。参考“Access Token获取”
二、应用中
1.获取 Access Token(Access Token的有效期(秒为单位,有效期30天);)
注意:Access Token是有有效期的,所以需要定时或者在打开页面时就获取它,我是在进入有识别的页面,每次后获取它
(1).方法:
// 获取 身份识别的 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: “替换成您管理应用中的 API Key”, //API Key
client_secret: “替换成您管理应用中的 Secret Key” //Secret Key
},
method: ‘POST’,
header: {
‘Content-Type’: ‘application/x-www-form-urlencoded’
},
success(res) {
_this.accessToken = res.data.access_token
console.error(“获取 身份识别的 accessToken = ” + JSON.stringify(_this.accessToken))
}
})
},
(2).调用:
onLoad() {
var _this = this
// 获取身份证识别的 accessToken
_this.getAccessToken()
},
(3).选择图片并识别身份证
这是布局中身份正反面布局以及点击事件(uploadImage参数传1:表示正面 2:表示反面)
选择并识别身份证方法:
// 身份证图片选择
uploadImage: function(ocrtype) {
var _this = this
var cardType = “”
if (ocrtype == 1) {
cardType = “front”
} else {
cardType = “back”
}
uni.chooseImage({
count: 1, //默认9
sizeType: [‘original’, ‘compressed’], //可以指定是原图还是压缩图,默认二者都有
sourceType: [‘album’], //从相册选择
success(res) {
var tempImg = res.tempFilePaths[0]
console.log(“选择图片路径 tempImg = ” + JSON.stringify(tempImg))
// 转base64
pathToBase64(res.tempFilePaths[0])
.then(base64 => {
// 识别
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’, //识别语言类型,默认中英文结合
detect_direction: true, //检测图像朝向
},
method: ‘POST’,
header: {
‘Content-Type’: ‘application/x-www-form-urlencoded’
},
success: (res) => {
console.error(“身份识别的信息 info = ” + JSON.stringify(res
.data))
if (ocrtype == 1) { //身份证正面
var cardName = res.data.words_result.姓名
if (cardName != undefined) {
_this.cardFrontParh = tempImg
_this.IDCardInfo.name = res.data.words_result
.姓名.words
_this.IDCardInfo.ethnic = res.data.words_result
.民族.words
_this.IDCardInfo.address = res.data
.words_result.住址.words
_this.IDCardInfo.idNumber = res.data
.words_result.公民身份号码.words
_this.IDCardInfo.birthday = res.data
.words_result.出生.words
_this.IDCardInfo.gender = res.data.words_result
.性别.words
} else {
uni.showToast({
title: “请选择正确或清晰的正面身份证图片”,
icon: “none”,
duration: 2000
})
}
} else {
var backName = res.data.words_result.签发机关
if (backName != undefined) {
_this.cardBackParh = tempImg
_this.IDCardInfo.signDate = res.data
.words_result.签发日期.words
_this.IDCardInfo.issueAuthority = res.data
.words_result.签发机关.words
_this.IDCardInfo.expiryDate = res.data
.words_result.失效日期.words
} else {
uni.showToast({
title: “请选择正确或清晰的反面身份证图片”,
icon: “none”,
duration: 2000
})
}
}
}
})
})
.catch(error => {
console.error(“error = ” + JSON.stringify(error))
})
}
})
},
(4).图片转base64
将图片转base64文件(img_transform_base64.js)放在/components/imgtobase64目录下
代码:
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’))
})
}
引用:在script中
<script>
import {
pathToBase64,
base64ToPath
} from “../../components/imgtobase64/img_transform_base64.js”
</script>
使用:
pathToBase64(res.tempFilePaths[0])
.then(base64 => {
console.log(“转成功后的base64 = ” + JSON.stringify(base64 ))
}).catch(error => {
console.error(“error = ” + JSON.stringify(error))
})
下面是文件大致代码介绍,其中代码上述都有
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119137.html