uniapp: 프런트 엔드는 Baidu Cloud OCR을 사용하여 텍스트 인식을 실현합니다(신분증 인식 기능, 기타 기능은 유사).

1장 서문

  • Baidu Smart Cloud를 사용하여 원하는 결과를 얻는 방법을 소개하려면 다음 URL에 계정을 등록해야 합니다.

Baidu Intelligent Cloud-Cloud-Intelligence 통합이 업계에 깊숙이 들어갑니다.

  • 사용 설명서는 다음 URL에 있습니다.

소개 - 텍스트 인식 OCR

  • 성공적인 요청의 효과는 다음과 같습니다. 

 

  •  제품 검색(예: 텍스트 인식) -> 지금 사용 -> 무료로 받기 -> 애플리케이션 만들기 (단계를 따르세요)

  • 성공적으로 생성되면 애플리케이션 목록은 아래와 같습니다.

  • 아래 표시된 대로 관리를 입력하세요. (상자의 내용은 사용해야 하는 필드입니다.)

제2장 실제 전투

  • 문서 요구 사항(액세스 토큰의 유효 기간(초 단위, 30일 동안 유효))에 따라 액세스 토큰을 얻습니다.
  • 참고: Access Token은 유효기간이 있으므로 정기적으로 또는 페이지를 열 때 획득해야 합니다.(로그인 페이지도 허용됩니다.) 편집자가 기능을 테스트 중이므로 식별된 페이지에 진입한 후 획득합니다.

코드는 다음과 같습니다. (uniapp의 기본 API입니다. 편집기에서는 코드의 모든 줄을 설명하지 않습니다. 자세한 내용은 공식 홈페이지를 참조하세요.)

<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>

참고: 여기의 요청은 세 가지 매개변수(grant_type, client_id, client_secret, grant_type)를 전달합니다. isclient_credentials ID 카드 식별을 나타냅니다. 고정 값은 공식 문서에 따라 직접 할당될 수 있습니다.client_id 및 client_secret는 첫 번째 장에서 동그라미로 표시된 두 필드에 해당합니다. 생성된 API Key와 Secret Key를 각각 적용

 참고: 편집기에서 컴파일한 일반적으로 사용되는 API

uniapp이 자주 사용하는 api_❆VE❆ 블로그 - CSDN 블로그

  • 액세스 토큰을 얻은 후 사진을 선택할 수 있습니다.
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))
				}
			})
		})
	},
}
  •  ID 카드 앞면과 뒷면에서 얻은 정보를 확인하기 위한 요청을 보냅니다.
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)
			}
		})
	},
}
  • 도메인 간 문제도 있다는 것을 잊지 마세요! ! ! 구성은 다음과 같습니다.
"h5" : {
   "devServer" : {
       "port" : 8000,
       "disableHostCheck" : true,
       "proxy" : {
           "/baiduApi" : {
               "target" : "https://aip.baidubce.com", // 需要跨域的域名
               "changeOrigin" : true,
               "secure" : false,
               "pathRewrite" : {
                    "^/baiduApi" : ""
                }
           }
       }
   },
}

 CORS 정책에 의해 차단된 https://aip.baidubce.com/oauth/2.0/token 오류 보고-CSDN 블로그

  • res 값을 살펴보겠습니다.

추천

출처blog.csdn.net/qq_45796592/article/details/133762635