OCR图片识别
本地ORC调用方式:
在线文档
0.postman接口调用(能用再进行下一步,替换下面的图片转base64)
URL:/api/ocr 请求方式:post 例:http://127.0.0.1:1224/api/ocr 入参: { "options": { "ocr.language": "models/config_chinese.txt", "ocr.cls": true, "ocr.limit_side_len": 4320, "tbpu.parser": "multi_none", "data.format": "text" }, "base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA" }1.前端vue代码
<a-col :span="24"> <a-form-model-item label="简要案情" :labelCol="labelTextCol" :wrapperCol="wrapperTextCol" prop="briefCase"> <a-textarea v-model="model.briefCase" rows="4" placeholder="请输入简要案情,简要案情需要包含时间,地点,人物,起因,经过,结果"/> <a-upload :beforeUpload="handleUpload" :showUploadList="false"> <a-button>上传图片提取文字</a-button> </a-upload> </a-form-model-item> </a-col> data() { return { model: { briefCase: '' }, } } handleUpload(file) { const isImage = file.type.startsWith('image/'); const isSizeValid = file.size / 1024 / 1024 <= 10; // 10MB // 检查文件格式和大小 if (!isImage) { this.$message.error("请上传图片格式的文件"); return false; // 阻止上传 } if (!isSizeValid) { this.$message.error("文件大小不能超过 10MB"); return false; // 阻止上传 } const formData = new FormData(); formData.append("file", file); postAction('/gridding/griddingCommitteeCase/recognize', formData, { headers: { "Content-Type": "multipart/form-data" }, }).then((res) => { if (res.code === 101) { // 如果返回的 code 是 101,表示没有提取到文本 this.$message.error("该图片没有提取到文本"); } else if (res.data) { // 如果有文本数据,更新 briefCase this.model.briefCase = this.model.briefCase + res.data; } }).catch(() => { this.$message.error("OCR 识别失败"); }); return false; // 阻止默认上传行为 }
2.后端java代码
@Value("${jeecg.path.ocrUrl}") private String ocrUrl; @PostMapping("/recognize") public JSONObject recognize(@RequestParam("file") MultipartFile file) throws IOException { // 1. 读取图片并转换为 Base64 String base64Image = Base64.getEncoder().encodeToString(file.getBytes()); // 2. 构造请求体 JSON JSONObject requestBodyJson = new JSONObject(); requestBodyJson.put("base64", base64Image); JSONObject options = new JSONObject(); options.put("ocr.language", "models/config_chinese.txt"); options.put("ocr.cls", true); options.put("ocr.limit_side_len", 4320); options.put("tbpu.parser", "multi_none"); options.put("data.format", "text"); requestBodyJson.put("options", options); // 3. 发送 HTTP 请求 OkHttpClient client = new OkHttpClient(); MediaType JSON_TYPE = MediaType.parse("application/json"); okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON_TYPE, requestBodyJson.toJSONString()); Request request = new Request.Builder() .url(ocrUrl) .post(body) .addHeader("Content-Type", "application/json") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("OCR 识别失败:" + response); } // 4. 解析返回数据 String responseBody = response.body().string(); return JSON.parseObject(responseBody); }注意:需要在model里添加该字段,才能实时更新
1521




被折叠的 条评论
为什么被折叠?



