赞
踩
要用百度ocr,就要先注册百度云,步骤如下。
1.注册百度云
2.进入百度云点击控制台
3.点击左侧菜单栏 文字识别 点击创建应用
4.点击创建应用,应用名称可以自己随意创建,文字识别包名根据自己需求选择需要还是不需要(我是uniapp,选择的不需要)
5.然后可以在应用管理查看自己建立的应用,里面有API Key和Secret Key,用于请求access_token。
6.然后就根据自己需要的识别功能的api 调用接口
封装请求
// 配置公共的URL路径 const Host = "https://aip.baidubce.com/"; // const Host = "/api" const http = (params) => { //返回promise 对象 return new Promise((resolve, reject) => { uni.request({ // 服务器url+参数中携带的接口具体地址 url:Host+params.url, // 请求参数 data: params.data, // 设置后端需要的常用的格式就好,特殊情况调用的时候单独设置 header: params.header || { "Content-Type": "application/json;charset=utf-8", "api-version": params.apiVersion ||'1.0' }, // "Authorization": token // 默认为GET,可以不写,如常用请求格式为POST,可以设置POST为默认请求方式 method: params.method && params.method.toUpperCase() || 'POST', dataType: params.dataType,//返回的数据格式,默认为JSON,特殊格式可以在调用的时候传入参数 responseType: params.responseType,//响应的数据类型 success: res => { // 接口访问正常返回数据 if ((res.statusCode == 200 && res.data.code === 200)||res.data.code === 401) { //1. 操作成功返回数据 resolve(res.data) } else { //2. 操作不成功返回数据,以toast方式弹出响应信息,如后端未格式化非操作成功异常信息,则可以统一定义异常提示 if(res.data.code === 503){ uni.showToast({ icon: "none", title: "系统异常", duration:3000 }) }else{ if(res.data.msg){ uni.showToast({ icon: "none", title: res.data.msg, duration:3000 }) } } resolve(res.data) } }, fail: function (e) { if(e.errMsg === "request:fail timeout"){ uni.showToast({ icon: "none", title: "网络连接超时,请稍后重试" }) } reject(e); setTimeout(() =>{ uni.hideLoading(); }, 1500) }, complete(e){ resolve(e) } }) }) } module.exports = { httpRequest: http }
写接口方法
import {httpRequest} from '../http.js' let url = { // 获取token getToken:'oauth/2.0/token', idCard:'rest/2.0/ocr/v1/idcard', } module.exports = { getTokenR(params){ return httpRequest({ url:`${url.getToken}?grant_type=client_credentials&client_id=7uermpcxy2CEmG8P3AbDlaIm&client_secret=tUCe8ks6YfFhegA6vH7MPUg0510nv0R9` }) }, getMessage(params){ return httpRequest({ url:`${url.idCard}?access_token=${params.access_token}`, data:params.data, header:{ "Content-Type":"application/x-www-form-urlencoded" } }) } }
编写页面调用接口
<template> <view class="content"> <button @click='choosePicture'>选择图片</button> <view v-if='showImg' style="width: 100%;height: 120px;"> <image v-for='item of chooseImgList' :src='item' class='chooseImg'></image> </view> <button @click='scan'>扫一扫</button> <text style="margin:20px;">扫描结果:{{res}}</text> <button @click='idCard'>上传身份证(正面)</button> <view class='idCardMessage'> <view>姓名:{{idCardMessageObj.name}}</view> <view>性别:{{idCardMessageObj.sex}}</view> <view>民族:{{idCardMessageObj.nation}}</view> <view>出生:{{idCardMessageObj.born}}</view> <view>住址:{{idCardMessageObj.address}}</view> <view>身份证号:{{idCardMessageObj.idNum}}</view> </view> </view> </template> <script> import {getTokenR,getMessage} from '@/api/index/index.js' import { pathToBase64, base64ToPath } from '@/component/image-tools/index.js' export default { data() { return { title: 'Hello', chooseImg:"", showImg:false, chooseImgList:[], picSrc:"", showIdCard:'', res:"", idCardMessageObj:{ name:"", sex:"", nation:"", born:"", address:"", idNum:"" } } }, onLoad() { }, methods: { choosePicture(){ uni.showLoading({ title: "上传中...", mask: true }) const that=this return new Promise((resolve,reject)=>{ uni.chooseImage({ count:9, sizeType: ['compressed'], success:function(e){ that.chooseImgList=e.tempFilePaths that.showImg=true; uni.hideLoading(); resolve(e) }, fail:function(e){ console.log('失败:',e) } }) }) }, scan(){ const that=this uni.scanCode({ success:function(result){ that.res=result.result console.log('成功',result.result) }, fail:function(res){ that.res=res console.log(res) } }) }, idCard(){ this.myToken() }, // 获取token myToken(){ this.choosePicture().then(res=>{ uni.showLoading({ title: "识别中...", mask: true }) const pic=res.tempFilePaths[0] let base64String // data:image/png;base64, // #ifdef MP-WEIXIN console.log('小程序') base64String = `${wx.getFileSystemManager().readFileSync(pic, "base64")}`; // #endif // #ifdef H5 console.log('H5') pathToBase64(pic) .then(base64 => { base64=base64.slice(23) base64String=base64 }) .catch(error => { console.error(error) }) // #endif getTokenR().then(res=>{ const params={ access_token:res.access_token, data:{ image: base64String, id_card_side: 'front' } } getMessage(params).then(r=>{ uni.hideLoading(); this.idCardMessageObj={ name:r.words_result.姓名.words, sex:r.words_result.性别.words, nation:r.words_result.民族.words, born:r.words_result.出生.words, address:r.words_result.住址.words, idNum:r.words_result.公民身份号码.words, } // console.log(this.idCardMessageObj) console.log(r) }) }) }) } } } </script> <style> .content{} .chooseImg{width: 100px;height:100px;display: inline-block;margin: 10px;float: left;} .idCardMessage{width: 100%;padding: 20px;box-sizing: border-box;} .idCardMessage view{width: 100%;min-height: 30px;line-height:30px;} </style>
这有一个组件将绝对路径图片转为base64位
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 } 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')) }) }
值得注意的是H5请求跨域就开启代理,小程序不需要
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。