uniapp: The front end uses Baidu Cloud OCR to realize text recognition (ID card recognition function, other functions are similar)

Chapter 1 Preface

  • To introduce how to use Baidu Smart Cloud to achieve the results we want, we need to register an account at the following URL:

Baidu Intelligent Cloud-Cloud-Intelligence integration goes deep into the industry

  • The usage documentation is at this URL:

Introduction - Text Recognition OCR

  • The effect of a successful request is as shown below: 

 

  •  Search for products (e.g. text recognition) -> Use now -> Get it for free -> Create application (Just follow the steps)

  • After successful creation, the application list is as shown below

  • Enter management, as shown below: (Note that the content of the box is the fields that need to be used)

Chapter 2 Actual Combat

  • Obtain the Access Token according to the document requirements (the validity period of the Access Token (in seconds, valid for 30 days);)
  • Note: Access Token has a validity period, so you need to obtain it regularly or when you open the page (the login page is also acceptable). The editor is testing the function, so I obtain it after entering the identified page.

The code is as follows: (These are the native APIs of uniapp. The editor will not explain every line of code. For details, please see the official website)

<template>
	<view class="content">
		<uni-nav-bar
			left-icon="back" 
			:fixed="true"
			@clickLeft="back2Index" 
			title="身份证测试平台"
			backgroundColor="#1677FF"
			height="88rpx"
			color="#fff"
			:border="false"
			safeAreaInsetTop></uni-nav-bar>
			<button @click="chooseImage">选择图片</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dataObj: {
					client_id: 'API Key',
					client_secret: 'Secret Key',
				},
				accessToken: ''
			}
		},
		onLoad() {
            // 方法调用
			this.getAccessToken()
		},
		methods: {
			// 百度云获取accessToken
			getAccessToken() {
				let self = this
                // 请求
				uni.request({
					url: '/baiduApi/oauth/2.0/token',
					data: {
						grant_type: 'client_credentials',
						client_id: self.dataObj.client_id,
						client_secret: self.dataObj.client_secret
					},
					dataType: "JSONP",
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
					},
					success: (res) => {
                        // 将得到的res先转对象,在.点出我们想要的值
						this.accessToken = JSON.parse(res.data).access_token
						console.log('accessToken', this.accessToken)
					},
					fail(err) {
						console.log("访问失败", err)
					}
				})
			},
			back2Index(){
				uni.navigateBack()
			},
		}
	}
</script>

Note: The request here carries three parameters: grant_type, client_id, client_secret, grant_type isclient_credentials represents ID card identification. The fixed value can be assigned directly according to the official document.client_id and client_secret correspond to the two fields circled in the first chapter. Apply the successfully created API Key and Secret Key respectively

 Note: Commonly used APIs compiled by the editor

uniapp commonly used api_❆VE❆'s blog-CSDN blog

  • After getting the Access Token, you can select pictures:
methods: {
    // 选择图片
	chooseImage() {
		let self = this
        // 这也是uniapp原生api
		uni.chooseImage({
			count: 1,
			success: (ress) => {
				uni.showLoading({
					title: '正在识别中...'
				})
				// 下面将图片本地路径转base64
				console.log('ress', ress)
				self.toBase64(ress.tempFilePaths[0]).then((res) => {
					console.log("res", res)
                    // 该函数是识别身份证的 也就是这个函数用到OCR百度云的接口
					self.uploadImage(res)
				})
			},
			fail(err) {
				uni.hideLoading()
				console.log(err)
			}
		})
	},
    // 转换为base64的函数
    toBase64(path){
		return new Promise((resolve, reject) => {
			uni.request({
				url: path,
				responseType: 'arraybuffer',
				success: (res) => {
					resolve(uni.arrayBufferToBase64(res.data))
				}
			})
		})
	},
}
  •  Send a request to identify the information obtained from the front and back of the ID card:
methods: {
    // 身份证识别
	uploadImage(path) {
		let self = this
		uni.request({
			url: '/baiduApi/rest/2.0/ocr/v1/idcard',
			data: {
				image: path, // 图片的base64路径
				access_token: self.accessToken, // Access Token
				id_card_side: 'front' // front身份证正面 back身份证反面
			},
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				uni.hideLoading()
				console.log('res', res) // 这就是调用百度云OCR接口成功返回的值
			},
			fail(err) {
				uni.hideLoading()
				console.log(err)
			}
		})
	},
}
  • Don’t forget that there are also cross-domain issues! ! ! The configuration is as follows:
"h5" : {
   "devServer" : {
       "port" : 8000,
       "disableHostCheck" : true,
       "proxy" : {
           "/baiduApi" : {
               "target" : "https://aip.baidubce.com", // 需要跨域的域名
               "changeOrigin" : true,
               "secure" : false,
               "pathRewrite" : {
                    "^/baiduApi" : ""
                }
           }
       }
   },
}

 https://aip.baidubce.com/oauth/2.0/token error reported blocked by CORS policy-CSDN Blog

  • Let’s take a look at the value of res

Guess you like

Origin blog.csdn.net/qq_45796592/article/details/133762635