阿里云OCR身份证信息识别
这里使用的是base64
public JSONObject getCard(MultipartFile file) {
String host = "https://ccic.market.alicloudapi.com";
String path = "/discern/idcard";
String method = "POST";
String appcode = "自己的appCode";
//生成文件的唯一id
String fileId = UUID.randomUUID().toString().replace("-","");
//获取文件后缀
String fileSuffix = file.getName().substring(file.getName().lastIndexOf(".")+1);
//生成文件的最终名称
String finalName = fileId + "." + fileSuffix;
try {
//保存文件到指定目录
String fileSavePath = "D:/upload/";
File newFile = new File(fileSavePath + finalName);
file.transferTo(newFile);
//url = "http://127.0.0.1/static/" + finalName;
//System.out.println(url);
String filePath = fileSavePath + finalName;
String base64 = ImageToBase64(filePath);
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求,定义相对应的Content-Type
headers.put("Content-Type", "application/json; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
String bodys = "{\"Base64Data\":"+'"'+ base64 +'"'+ ",\"Category\":\"front\"}";
//String bodys ="{\"ImageUrl\":"+'"'+ url +'"'+",\"Category\":\"front\"}";
//System.out.println(bodys);
try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
//Object json = JSONObject.toJSON(code);
System.out.println(jsonObject);
return jsonObject;
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 本地图片转换Base64的方法
*
* @param imgPath
* @return
*/
private static String ImageToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
//System.out.println("本地图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
return encoder.encode(Objects.requireNonNull(data));
}