目录
一、在阿里云申请ocr识别服务
二、创建springboot项目
三、后续
一、在阿里云申请ocr识别服务
在线体验:房产证图片上传
[阿里官方]不动产权证OCR文字识别_API专区_云市场-阿里云 (aliyun.com)
可以选择一毛500次这个
当然也可以白嫖100
下面有个在线调试,类似于apifox/postman,在线的发送http请的网站,这里你可以看到post请求的url是,httpbody部分需要一个json格式的字符串
二、创建springboot项目
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.3</version> <!-- 使用最新版本 --></dependency>
okhttp主要是模拟对阿里云接口发送http请求
需要对图片进行base64转码
@RestController
@RequestMapping("/ocr")
public class OcrController {@Autowiredprivate OwnershipService ownershipService;@RequestMapping("/ownership")public String ownershipCertificate(@RequestParam("file") MultipartFile file) throws IOException {System.out.println(file.getOriginalFilename());return ownershipService.getData(file.getBytes());}
}
base64图片转码
这里重写两种转码方式
public class ImageToBase64 {public static String imageToBase64(String imagePath) throws IOException {File file = new File(imagePath);byte[] bytes = new byte[(int) file.length()];try (FileInputStream fis = new FileInputStream(file)) {fis.read(bytes);}return Base64.getEncoder().encodeToString(bytes);}public static String imageToBase64(byte[] bytes) throws IOException {return Base64.getEncoder().encodeToString(bytes);}
}
service层
@Service
public class OwnershipService {@Autowiredprivate OkHttpClient okHttpClient;@Autowiredprivate ObjectMapper objectMapper;private String appcode = "自己申请的";public String getData(byte[] imageBody) {String ret = "";try {// 1. 准备请求体ImageBody body = new ImageBody();body.setImg(ImageToBase64.imageToBase64(imageBody));// 2. 确保APPCODE正确// 3. 创建请求MediaType JSON = MediaType.get("application/json; charset=utf-8");String jsonBody = objectMapper.writeValueAsString(body);Request request = new Request.Builder().url("https://bdcqz.market.alicloudapi.com/ocrservice/estateCert").post(RequestBody.create(jsonBody, JSON)).addHeader("Authorization", "APPCODE " + appcode).addHeader("Content-Type", "application/json; charset=UTF-8").build();// 4. 执行请求并处理响应try (Response response = okHttpClient.newCall(request).execute()) {if (!response.isSuccessful()) {String errorBody = response.body().string();throw new IOException("API请求失败:\n" +"状态码: " + response.code() + "\n" +"错误信息: " + response.message() + "\n" +"响应体: " + errorBody);}ret = response.body().string();System.out.println("识别结果: " + ret);}} catch (Exception e) {System.err.println("发生错误: " + e.getMessage());e.printStackTrace();}return ret;}
}
okhttp记得交给spring来管理
@Configuration
public class OkHttpConfig {@Beanpublic OkHttpClient okHttpClient() {OkHttpClient okHttpClient = new OkHttpClient();return okHttpClient;}
}
index,html
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>房产证图片上传</title><style>body {font-family: 'Microsoft YaHei', Arial, sans-serif;background-color: #f5f5f5;margin: 0;padding: 20px;color: #333;}.container {max-width: 800px;margin: 0 auto;background-color: #fff;padding: 30px;border-radius: 8px;box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);}h1 {color: #2c3e50;text-align: center;margin-bottom: 30px;}.upload-area {border: 2px dashed #3498db;border-radius: 5px;padding: 30px;text-align: center;margin-bottom: 20px;cursor: pointer;transition: all 0.3s;}.upload-area:hover {background-color: #f0f8ff;border-color: #2980b9;}.upload-icon {font-size: 48px;color: #3498db;margin-bottom: 15px;}.upload-text {font-size: 16px;margin-bottom: 10px;}.file-input {display: none;}.preview-container {display: none;margin-top: 20px;text-align: center;}.preview-image {max-width: 100%;max-height: 400px;border-radius: 5px;box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);}.btn {background-color: #3498db;color: white;border: none;padding: 12px 24px;font-size: 16px;border-radius: 5px;cursor: pointer;transition: background-color 0.3s;display: block;margin: 20px auto 0;}.btn:hover {background-color: #2980b9;}.requirements {margin-top: 30px;padding: 15px;background-color: #f8f9fa;border-radius: 5px;font-size: 14px;}.requirements h3 {margin-top: 0;color: #2c3e50;}.error-message {color: #e74c3c;text-align: center;margin-top: 10px;display: none;}</style><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
</head>
<body>
<div class="container"><h1>OCR-房产证图片上传</h1><div class="requirements"><h3>上传要求:</h3><ul><li>请上传清晰、完整的房产证图片</li><li>图片需包含房产证全部内容,无遮挡</li><li>确保图片光线充足,文字清晰可辨</li><li>支持 JPG、PNG 格式,大小不超过 5MB</li><li>请勿上传与房产证无关的图片</li></ul></div><div class="upload-area" id="uploadArea"><div class="upload-icon">📁</div><div class="upload-text">点击或拖拽房产证图片到此处</div><div class="upload-subtext">支持 JPG、PNG 格式,大小不超过 5MB</div><input type="file" id="fileInput" class="file-input" accept="image/jpeg, image/png"></div><div class="error-message" id="errorMessage"></div><div class="preview-container" id="previewContainer"><img id="previewImage" class="preview-image" src="#" alt="房产证预览"><button class="btn" id="uploadBtn">确认上传</button></div><div class="result"></div></div><script>const uploadArea = document.getElementById('uploadArea');const fileInput = document.getElementById('fileInput');const previewContainer = document.getElementById('previewContainer');const previewImage = document.getElementById('previewImage');const uploadBtn = document.getElementById('uploadBtn');const errorMessage = document.getElementById('errorMessage');let selectedFile = null;// 点击上传区域触发文件选择uploadArea.addEventListener('click', () => {fileInput.click();});// 拖放功能uploadArea.addEventListener('dragover', (e) => {e.preventDefault();uploadArea.style.backgroundColor = '#f0f8ff';uploadArea.style.borderColor = '#2980b9';});uploadArea.addEventListener('dragleave', () => {uploadArea.style.backgroundColor = '';uploadArea.style.borderColor = '#3498db';});uploadArea.addEventListener('drop', (e) => {e.preventDefault();uploadArea.style.backgroundColor = '';uploadArea.style.borderColor = '#3498db';if (e.dataTransfer.files.length) {handleFile(e.dataTransfer.files[0]);}});// 文件选择处理fileInput.addEventListener('change', () => {if (fileInput.files.length) {handleFile(fileInput.files[0]);}});// 处理选择的文件function handleFile(file) {// 验证文件类型const validTypes = ['image/jpeg', 'image/png'];if (!validTypes.includes(file.type)) {showError('请上传 JPG 或 PNG 格式的图片');return;}// 验证文件大小 (5MB)if (file.size > 5 * 1024 * 1024) {showError('图片大小不能超过 5MB');return;}selectedFile = file;// 预览图片const reader = new FileReader();reader.onload = (e) => {previewImage.src = e.target.result;previewContainer.style.display = 'block';errorMessage.style.display = 'none';};reader.readAsDataURL(file);}// 显示错误信息function showError(message) {errorMessage.textContent = message;errorMessage.style.display = 'block';previewContainer.style.display = 'none';}// 上传按钮点击事件uploadBtn.addEventListener('click', () => {// 这里添加实际上传逻辑alert('房产证图片已上传,正在识别中');const formData = new FormData();formData.append('file', selectedFile);$.ajax({url: '/ocr/ownership',type: 'POST',data: formData,processData: false,contentType: false,success: function (data) {let jsonData = JSON.parse(data);console.log(jsonData)let resultDiv = document.querySelector('.result');let str = '<h1>' + 'OCR-房产证-识别结果';for (let val of jsonData.prism_keyValueInfo) {if (val.value != null && val.value.length > 0){str += '<h2>' + val.key + ': ' + val.value + '</h2>'}}resultDiv.innerHTML = str;}});});
</script>
</body>
</html>
三、后续
- 增加其他ocr识别服务
- 增加统一结果返回
- 统一处理全局异常
- 增加在pom文件处统一管理appcode