1、获取AccessKey ID&Access Key Secret
调用阿里云sdk首先需要创建自己阿里云账号,取得AccessKey 和 Access Key Secret的值,这两个参数都是sdk调用必须的。
2、开通内容安全服务
(aliyun OCR给我们每个账号提供5000条免费次数,后面需要续费)
同时如果使用本地文件或者二进制文件检测,需要在项目工程中引入Extension.Uploader工具类。
3、代码实现
首先pom文件引入依赖:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-green</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
1)同步图文识别---远程图片url (参数为远程图片url)
private String aliyunOcrCheckTb(String url) throws Exception {
String result = "";
IClientProfile iClientProfile = DefaultProfile.getProfile("cn-shanghai", "YOUR AccessKey ID", "YOUR Access Key Secret");
IAcsClient client = new DefaultAcsClient(iClientProfile);
ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
// 指定返回格式
imageSyncScanRequest.setSysAcceptFormat(FormatType.JSON);
// 指定请求方法(sysMethod,setEncoding,setProtocol)
imageSyncScanRequest.setSysMethod(MethodType.POST);
imageSyncScanRequest.setSysEncoding("utf-8");
List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
Map<String, Object> taskMap = new LinkedHashMap<String, Object>();
taskMap.put("dataId", UUID.randomUUID().toString());
taskMap.put("url", url);
taskMap.put("time", new Date());
taskList.add(taskMap);
JSONObject jsonData = new JSONObject();
// 设置检测场景-ocr图文检测
jsonData.put("scenes", "ocr");
jsonData.put("tasks", taskList);
imageSyncScanRequest.setHttpContent(jsonData.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
// 设置超时时间
imageSyncScanRequest.setSysConnectTimeout(3000);
imageSyncScanRequest.setSysReadTimeout(6000);
try {
HttpResponse httpResponse = client.doAction(imageSyncScanRequest);
if (httpResponse.isSuccess()) {
JSONObject srcResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
if (codeSucc == srcResponse.getInteger("code")) {
JSONArray taskResults = srcResponse.getJSONArray("data");
for (Object taskResult : taskResults) {
String scene = ((JSONObject)taskResult).getString("scene");
String suggestion = ((JSONObject)taskResult).getString("suggestion");
if ("review".equals(suggestion) && "ocr".equals(scene)) {
JSONArray ocrDatas = ((JSONObject) taskResult).getJSONArray("ocrData");
for (Object ocrData:ocrDatas) {
result = (String) ocrData;
}
}
}
} else {
System.out.println("detect not success. code:" + srcResponse.getInteger("code"));
}
} else {
System.out.println("response not success. status:" + httpResponse.getStatus());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2)同步图文识别---本地图片url (参数为本地图片url)
private String aliyunOcrCheckTbLocal(String localUrl) throws Exception {
String result = "";
IClientProfile iClientProfile = DefaultProfile.getProfile("cn-shanghai", "YOUR AccessKey ID", "YOUR Access Key Secret");
IAcsClient client = new DefaultAcsClient(iClientProfile);
ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
// 指定返回格式
imageSyncScanRequest.setSysAcceptFormat(FormatType.JSON);
// 指定请求方法(sysMethod,setEncoding,setProtocol)
imageSyncScanRequest.setSysMethod(MethodType.POST);
imageSyncScanRequest.setSysEncoding("utf-8");
ClientUploader clientUploader = ClientUploader.getImageClientUploader(iClientProfile, false);
String url = null;
try{
url = clientUploader.uploadFile(localUrl);
}catch (Exception e){
System.out.println("upload file to server fail.");
}
List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
Map<String, Object> taskMap = new LinkedHashMap<String, Object>();
taskMap.put("dataId", UUID.randomUUID().toString());
taskMap.put("url", url);
taskMap.put("time", new Date());
taskList.add(taskMap);
JSONObject jsonData = new JSONObject();
// 设置检测场景-ocr图文检测
jsonData.put("scenes", "ocr");
jsonData.put("tasks", taskList);
imageSyncScanRequest.setHttpContent(jsonData.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
// 设置超时时间
imageSyncScanRequest.setSysConnectTimeout(3000);
imageSyncScanRequest.setSysReadTimeout(6000);
try {
HttpResponse httpResponse = client.doAction(imageSyncScanRequest);
if (httpResponse.isSuccess()) {
JSONObject srcResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
if (codeSucc == srcResponse.getInteger("code")) {
JSONArray taskResults = srcResponse.getJSONArray("data");
for (Object taskResult : taskResults) {
if(codeSucc == ((JSONObject)taskResult).getIntValue("code")){
JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
for (Object sceneResult : sceneResults) {
String scene = ((JSONObject)sceneResult).getString("scene");
String suggestion = ((JSONObject)sceneResult).getString("suggestion");
if ("review".equals(suggestion) && "ocr".equals(scene)) {
JSONArray ocrDatas = ((JSONObject) sceneResult).getJSONArray("ocrData");
for (Object ocrData:ocrDatas) {
result = (String) ocrData;
}
}
}
} else {
System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
}
}
} else {
System.out.println("detect not success. code:" + srcResponse.getInteger("code"));
}
} else {
System.out.println("response not success. status:" + httpResponse.getStatus());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
3)同步图文高精度识别---本地图片url
参考API,高精度识别需要多传一个参数
private String aliyunOcrCheckTbLocalHigh(String localUrl) throws Exception {
String result = "";
IClientProfile iClientProfile = DefaultProfile.getProfile("cn-shanghai", "YOUR AccessKey ID", "YOUR Access Key Secret");
IAcsClient client = new DefaultAcsClient(iClientProfile);
ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
// 指定返回格式
imageSyncScanRequest.setSysAcceptFormat(FormatType.JSON);
// 指定请求方法(sysMethod,setEncoding,setProtocol)
imageSyncScanRequest.setSysMethod(MethodType.POST);
imageSyncScanRequest.setSysEncoding("utf-8");
ClientUploader clientUploader = ClientUploader.getImageClientUploader(iClientProfile, false);
String url = null;
try{
url = clientUploader.uploadFile(localUrl);
}catch (Exception e){
System.out.println("upload file to server fail.");
}
List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
Map<String, Object> taskMap = new LinkedHashMap<String, Object>();
taskMap.put("dataId", UUID.randomUUID().toString());
taskMap.put("url", url);
taskMap.put("time", new Date());
taskList.add(taskMap);
// ocr高精度识别必需参数 -- "extras": {"type": "advanced"}
JSONObject high = new JSONObject();
high.put("type", "advanced");
JSONObject jsonData = new JSONObject();
// 设置检测场景-ocr图文检测
jsonData.put("scenes", "ocr");
jsonData.put("extras", high);
jsonData.put("tasks", taskList);
imageSyncScanRequest.setHttpContent(jsonData.toJSONString().getBytes(StandardCharsets.UTF_8), "UTF-8", FormatType.JSON);
// 设置超时时间
imageSyncScanRequest.setSysConnectTimeout(3000);
imageSyncScanRequest.setSysReadTimeout(6000);
try {
HttpResponse httpResponse = client.doAction(imageSyncScanRequest);
if (httpResponse.isSuccess()) {
JSONObject srcResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), StandardCharsets.UTF_8));
if (codeSucc == srcResponse.getInteger("code")) {
JSONArray taskResults = srcResponse.getJSONArray("data");
for (Object taskResult : taskResults) {
if(codeSucc == ((JSONObject)taskResult).getIntValue("code")){
JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
for (Object sceneResult : sceneResults) {
String scene = ((JSONObject)sceneResult).getString("scene");
String suggestion = ((JSONObject)sceneResult).getString("suggestion");
if ("review".equals(suggestion) && "ocr".equals(scene)) {
JSONArray ocrDatas = ((JSONObject) sceneResult).getJSONArray("ocrData");
for (Object ocrData:ocrDatas) {
result = (String) ocrData;
}
}
}
} else {
System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
}
}
} else {
System.out.println("detect not success. code:" + srcResponse.getInteger("code"));
}
} else {
System.out.println("response not success. status:" + httpResponse.getStatus());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
4)异步图文识别---远程图片url (参数为远程图片url)
①异步检测
异步检测会返回一个taskId,后续我们通过taskId来获取检测的结果
private String aliyunOcrCheckYb(String url) throws Exception {
String result = "";
IClientProfile iClientProfile = DefaultProfile.getProfile("cn-shanghai", "YOUR AccessKey ID", "YOUR Access Key Secret");
IAcsClient client = new DefaultAcsClient(iClientProfile);
ImageAsyncScanRequest imageAsyncScanRequest = new ImageAsyncScanRequest();
imageAsyncScanRequest.setSysAcceptFormat(FormatType.JSON);
imageAsyncScanRequest.setSysMethod(com.aliyuncs.http.MethodType.POST);
imageAsyncScanRequest.setSysEncoding("utf-8");
List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
Map<String, Object> taskMap = new LinkedHashMap<String, Object>();
taskMap.put("dataId", UUID.randomUUID().toString());
taskMap.put("url", url);
taskMap.put("time", new Date());
taskList.add(taskMap);
JSONObject jsonData = new JSONObject();
// 设置检测场景-ocr图文检测
jsonData.put("scenes", "ocr");
jsonData.put("tasks", taskList);
imageAsyncScanRequest.setHttpContent(jsonData.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
// 设置超时时间
imageAsyncScanRequest.setSysConnectTimeout(3000);
imageAsyncScanRequest.setSysReadTimeout(6000);
try {
HttpResponse httpResponse = client.doAction(imageAsyncScanRequest);
if (httpResponse.isSuccess()) {
JSONObject srcResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
if (codeSucc == srcResponse.getInteger("code")) {
JSONArray taskResults = srcResponse.getJSONArray("data");
for (Object taskResult : taskResults) {
if (codeSucc == ((JSONObject) taskResult).getInteger("code")) {
String taskId = ((JSONObject) taskResult).getString("taskId");
result = taskId;
} else {
System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
}
}
} else {
System.out.println("detect not success. code:" + srcResponse.getInteger("code"));
}
} else {
System.out.println("response not success. status:" + httpResponse.getStatus());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
②通过taskId获取异步检测结果
private String getResult(HttpResponse httpResponse) throws Exception {
String result = "";
if(httpResponse != null && httpResponse.isSuccess()){
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(),"UTF-8"));
System.out.println(JSON.toJSONString(scrResponse));
int requestCode = scrResponse.getIntValue("code");
// 每一张图片的检测结果。
JSONArray taskResults = scrResponse.getJSONArray("data");
if (codeSucc == requestCode) {
for (Object taskResult : taskResults) {
// 单张图片的处理结果。
int taskCode = ((JSONObject)taskResult).getIntValue("code");
// 对应检测场景下图片的处理结果。如果是多个场景,则会有每个场景的结果。
JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
if(codeSucc == taskCode){
for (Object sceneResult : sceneResults) {
String scene = ((JSONObject)sceneResult).getString("scene");
String suggestion = ((JSONObject)sceneResult).getString("suggestion");
System.out.println("suggestion:--------" + suggestion);
if ("review".equals(suggestion) && "ocr".equals(scene)) {
//代表结果获取成功
//按自己需求do something
JSONArray ocrDatas = ((JSONObject) sceneResult).getJSONArray("ocrData");
for (Object ocrData:ocrDatas) {
result = (String) ocrData;
}
}
}
}else{
// 单张图片处理失败,原因视具体的情况详细分析。
System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
}
}
} else {
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
}
}
return result;
}
不过,目前异步获取结果出现:
因为是初学者,所以不太懂为什么,有懂哥可以回答下什么原因吗,万分感谢!!
整个实现过程也参考了:https://blog.csdn.net/csdn_ljl/article/details/99677488 的内容。