uniapp开发的app中怎么对接百度云免费文字识别

85 阅读2分钟

项目中开发这个功能,记录一下使用这个功能步骤,以及踩过的坑,和各位技术大佬互相探讨

1:项目中有文字识别功能,本来想用腾讯云的OCR文字识别,无奈测试了一上午没调通,果断选择百度云的OCR文字识别,不过在测试阶段也踩过坑,上传的图片地址有错误,这块下面会说明,下面就是步骤:

一:注册百度云账号并创建项目

1:访问百度云官方网站并注册一个账号

2:登录后,创建一个应用,并在项目中获取你的API KeySecret Key

1748943505962.png

二:将申请的AppIdAPI KeySecret Key 在项目的anifest.json中配置

image.png

三:新建一个js文件,将文字识别封装一个公共的函数

import {
	pathToBase64,
	base64ToPath
} from 'image-tools' //下载处理图片地址,将图片地址转为base64格式
export async function textIdentify(filePath, callback) {
	pathToBase64(filePath)
		.then(base64 => {
			ocrImage(base64, callback);
		})
		.catch(error => {
			console.error(error)
		})


}
async function ocrImage(image, callback) {
	let that = this
	const accessToken = await getAccessToken(); // 获取access_token
	const url =
		'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'; // OCR接口URL https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic
	const params = {
		access_token: accessToken, // 使用获取的access_token
		image: image // 或者图片的URL(根据API要求)
	};
	try {
		const response = await uni.request({
			url,
			method: 'POST',
			data: params,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			} // 根据API要求设置正确的Content-Type
		});
		console.log(response[1], '文字识别的结果呢'); // 打印响应数据,包含识别的文字结果等。
		let resultText = ''

		response[1].data.words_result.forEach((item) => {
			resultText = resultText + item.words
		})
		callback(resultText)

	} catch (error) {
		console.error(error);
	}

}

async function getAccessToken() {
	const url = 'https://aip.baidubce.com/oauth/2.0/token';
	const params = {
		grant_type: 'client_credentials', // 固定值,用于获取access_token的方式
		client_id: '你的ID', // AK(Access Key ID)
		client_secret: '你的key' // SK(Secret Access Key)
	};
	try {
		const response = await uni.request({
			url,
			method: 'POST',
			data: params,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			}
		});
		return response[1].data.access_token; // 返回access_token
	} catch (error) {
		console.error(error);
	}
}


四:在有文字识别的页面中调用

<script>
import {
		textIdentify
	} from "@/utils/identify";
	export default {
		name: "dictDrugHandle",
		data() {
			return {
				form: {
					describe: ""
				},
			};
		},
		onShow() {
		},
		onLoad(option) {
			
		},

		methods: {
			identifyText() {
				let that = this
				uni.chooseImage({
					success(chooseImageRes) {

						const tempFilePaths = chooseImageRes.tempFilePaths;
						const filePath = tempFilePaths[0]; // 获取第一张图片的路径

						textIdentify(filePath, (resultText) => {
							that.form.describe = resultText
							console.log(that.form.describe)
							that.$forceUpdate()
						})
					}
				})
			},}

</script>


用百度云的OCR文字识别,免费的次数有限制,具体的可以看官网,这是我使用的百度云的经验,大家有问题可以留言交流哟