本文是调用微软OCR api的一些经验和代码记录:
微软OCR api的地址:https://docs.azure.cn/zh-cn/cognitive-services/computer-vision/quickstarts/java
其中包含各种语言、各种服务的调用示例:
本文主要是传入图片url或者图片stream来获取识别文本的response,通过response来实现自己的业务逻辑。
核心代码:
@Service(value = "azureOcrService")
public class DefaultAzureOcrService implements AzureOcrService {
private static final Logger logger = Logger.getLogger("DefaultAzureOcrService");
// Replace the subscriptionKey string value with your valid subscription key.
public static final String subscriptionKey = "13hc77781f7e4b19b5fcdd72a8df7156";
// if you want to use the celebrities model, change "landmarks" to "celebrities" here and in
// uriBuilder.setParameter to use the Celebrities model.
public static final String uriBase = "https://api.cognitive.azure.cn/vision/v1.0/ocr";
@Autowired
private HttpUtils httpUtils;
@Override
public String getSerialNumber(String url,InputStream inputStream) {
HttpClient httpClient = new DefaultHttpClient();
String serialNumber = null;
try
{
URIBuilder uriBuilder = new URIBuilder(uriBase);
uriBuilder.setParameter("language", "unk");
uriBuilder.setParameter("detectOrientation ", "true");
// Request parameters.
URI uri = uriBuilder.build();
HttpPost request = new HttpPost(uri);
// Request headers.
request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
// Request body.
if (url!=null){
request.setHeader("Content-Type", "application/json");
StringEntity requestEntity = new StringEntity("{\"url\":\""+url+"\"}");
request.setEntity(requestEntity);
}else {
request.setHeader("Content-Type", "application/octet-stream");
InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream);
request.setEntity(inputStreamEntity);
}
// Execute the REST API call and get the response entity.
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
// Format and display the JSON response.
String jsonString = EntityUtils.toString(entity);
JSONObject json = new JSONObject(jsonString);
System.out.println("REST Response:\n");
System.out.println(json.toString(2));
}
}
catch (Exception e)
{
// Display error message.
logger.info(e.getMessage());
}
return serialNumber;
}
}
最好业务实现获取serialNumber可以通过response json来读取和判断。
代码主要是通过写controller 来获取image url、stream来实现图片的识别。(AzureOcrController是OCR的入口)
代码链接:https://github.com/Jacob029049/JWT
如果文中有什么错误,欢迎指出,以免更多的人被误导。谢谢。