【vue + JS】OCR图片识别、文字识别
一、需求说明
将上传图片中的文字内容识别出来
二、需求分析
利用“百度文字识别”功能,将上传的图片转成base64格式,调取对应的识别接口获取图片上的文字。
- 上传图片
- 将图片转换成base64格式
- 获取图片识别所需的token
- 执行OCR图片识别
三、解决方法
1、html:上传图片按钮
<a-uploadaccept=".png,.jpg":beforeUpload="beforeUploadFile"@reject="message.warning('上传文件格式不正确')":showUploadList="false"
><a-button class="btn-bg"><svg-icon icon-class="upload" class="btn-icon"></svg-icon>上传照片识别</a-button>
</a-upload>
2、js:实现功能方法
// 环境变量配置
const API_KEY = "xxx";
const SECRET_KEY = "xxx";const loading = ref(false);
const imageData = ref<string | ArrayBuffer | null>(null);
const result = ref(null);/*** @description: 将上传的图片转换成base64格式* @param {object} file 文件* @return {*}*/
const handleFileChange = (file: any) => {resultData.isLeft = false;let fr = new FileReader();fr.readAsDataURL(file); // 读取文件并返回DataURLfr.onload = function () {imageData.value = fr.result; // 获取Base64编码};setTimeout(() => {recognizeImage(); //识别图片}, 500);
};/*** @description: 利用百度OCR识别api文档,进行图片识别* @return {*}*/
const recognizeImage = async () => {if (!imageData.value) return;loading.value = true;try {const accessToken = await getAccessToken();const params = new URLSearchParams();params.append("image", imageData.value as string);params.append("detect_direction", "true"); // 自动旋转检测:ml-citation{ref="4" data="citationList"}const response = await axios.post("/baiduApi/rest/2.0/ocr/v1/accurate_basic", params, {params: { access_token: accessToken },headers: { "Content-Type": "application/x-www-form-urlencoded" }});// response.data.words_result 识别出的文字result.value = response.data.words_result as any;} catch (error) {handleError(error);// 错误处理} finally {loading.value = false;}
};/*** @description: 错误处理* @return {*}*/
const handleError = (error: any) => {if (error.response?.data?.error_code) {const errorCode = error.response.data.error_code;switch (errorCode) {case 18:alert("API调用频率超限");break;case 216202:alert("未检测到图片有效内容");break;default:alert(`识别失败,错误码:${errorCode}`);}}
};/*** @description: 获取图片识别所需的token* @return {*}*/
const getAccessToken = async () => {try {const response = await axios.post("/baiduApi/oauth/2.0/token", null, {params: {grant_type: "client_credentials",client_id: API_KEY,client_secret: SECRET_KEY}});return response.data.access_token;} catch (error) {console.error("获取Token失败:", error);throw error;}
};
PS:注意跨域问题
vite.config.ts 文件中设置代理
server: {host: "0.0.0.0",port: 4000, // 设置服务启动端口号open: false, // 设置服务启动时是否自动打开浏览器cors: true, // 允许跨域hmr: true,// 设置代理,根据我们项目实际情况配置proxy: {"/baiduApi": {target: "https://aip.baidubce.com",changeOrigin: true,secure: false, // 关闭SSL证书验证:ml-citation{ref="3,4" data="citationList"}rejectUnauthorized: false, // 允许自签名证书:ml-citation{ref="3,4" data="citationList"}rewrite: path => path.replace(/^\/baiduApi/, "")}} }
四、参考链接
百度文档:文字识别OCR