java代码 ocr文字识别
时间: 2023-11-23 16:55:27 浏览: 130
OCR文字识别.zip
以下是Java实现OCR文字识别的代码示例:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class OCRDemo {
public static void main(String[] args) {
try {
URL url = new URL("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
String param = "image=" + URLEncoder.encode(getImageStr("test.png"), "UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(param.getBytes());
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
System.out.println(stringBuilder.toString());
bufferedReader.close();
inputStream.close();
connection.disconnect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String getImageStr(String imagePath) {
String imageStr = "";
try {
File file = new File(imagePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
imageStr = Base64.getEncoder().encodeToString(bytes);
fileInputStream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return imageStr;
}
}
```
这段代码使用了百度云OCR API进行文字识别,需要先在百度云平台上注册并创建应用,获取API Key和Secret Key。代码中的`test.png`为需要识别的图片文件名,可以根据实际情况进行修改。
阅读全文