第一种:阿里官方,需要引入阿里的sdk
pom文件里加依赖
```
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>ocr20191230</artifactId>
<version>2.0.0</version>
</dependency>
```
controller接口直接调用
```
public static com.aliyun.ocr20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
初始化配置对象com.aliyun.teaopenapi.models.Config
Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret)
// 访问的域名
config.endpoint = "ocr.cn-shanghai.aliyuncs.com"
return new com.aliyun.ocr20191230.Client(config)
}
public void aliVehiclePlate() throws Exception {
UploadFile uploadFile = getFile()
if(uploadFile == null){
renderJson(Result.failed("请上传一张图片"))
return
}
File file = uploadFile.getFile()
String filePath = file.getPath()
String accessKeyId = Config.configprop.get("ali_access_key_id","")
String accessKeySecret = Config.configprop.get("ali_access_key_secret","")
if(StrKit.isBlank(accessKeyId) || StrKit.isBlank(accessKeySecret)){
renderJson(Result.failed("accessKeyId和accessKeySecret 没有设置"))
return
}
// 创建AccessKey ID和AccessKey Secret,请参见:https://help.aliyun.com/document_detail/175144.html
// 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参见:https://help.aliyun.com/document_detail/145025.html
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
com.aliyun.ocr20191230.Client client = createClient(accessKeyId, accessKeySecret)
// 场景一,使用本地文件
InputStream inputStream = new FileInputStream(file)
// 场景二,使用任意可访问的url
// URL url = new URL("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeLicensePlate/cpsb1.jpg")
// InputStream inputStream = url.openConnection().getInputStream()
com.aliyun.ocr20191230.models.RecognizeLicensePlateAdvanceRequest recognizeLicensePlateAdvanceRequest = new com.aliyun.ocr20191230.models.RecognizeLicensePlateAdvanceRequest()
.setImageURLObject(inputStream)
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions()
try {
// 复制代码运行请自行打印 API 的返回值
RecognizeLicensePlateResponse response = client.recognizeLicensePlateAdvance(recognizeLicensePlateAdvanceRequest, runtime)
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)))
if(response.getStatusCode() == 200){
String plateNumber = response.getBody().getData().getPlates().get(0).getPlateNumber()
renderJson(Result.success(plateNumber))
return
}
renderJson(Result.failed("识别不到车牌号"))
} catch (TeaException error) {
// 获取整体报错信息
System.out.println(com.aliyun.teautil.Common.toJSONString(error))
// 获取单个字段
System.out.println(error.getCode())
error.printStackTrace()
renderJson(Result.failed("识别不到车牌号"))
}finally {
if(inputStream != null){
inputStream.close()
}
file.delete()
}
}
```
第二种:非阿里官方,不需要额外引入jar
controller接口
// controller接口
public void aliVehiclePlate() {
String appcode = Config.configprop.get("ali_ocr_appcode","c8e7518fd8414deab136baf6b2233356")
if(StrKit.isBlank(appcode)){
renderJson(Result.failed("阿里识别车牌号的AppCode 没有设置"))
return
}
UploadFile uploadFile = getFile()
if(uploadFile == null){
renderJson(Result.failed("请上传一张图片"))
return
}
File file = uploadFile.getFile()
String path = file.getPath()
try{
String vehiclePlate = this.aliVehiclePlate(appcode, file)
if(StrKit.isBlank(vehiclePlate)){
renderJson(Result.failed("识别不到车牌号"))
}else{
renderJson(Result.success(vehiclePlate))
}
}finally {
file.delete()
}
}
```
/**
* 阿里OCR-车牌识别
* @param appcode 你的APPCODE
* @param imgFile 图片地址
*/
private String aliVehiclePlate(String appcode , String imgFile){
return this.aliVehiclePlate(appcode,null,imgFile)
}
/**
* 阿里OCR-车牌识别
* @param appcode 你的APPCODE
* @param file 图片文件
*/
private String aliVehiclePlate(String appcode , File file){
return this.aliVehiclePlate(appcode,file,null)
}
```
```
/**
* 阿里OCR-车牌识别
* @param appcode 你的APPCODE
* @param imgFile
*/
private String aliVehiclePlate(String appcode , File file, String imgFile){
String host = "https://ocrcp.market.alicloudapi.com"
String path = "/rest/160601/ocr/ocr_vehicle_plate.json"
//请根据线上文档修改configure字段
JSONObject configObj = new JSONObject()
//当设成true时, 只返回车牌号置信度较高,且车牌号位数大于等于7位的结果
configObj.put("multi_crop", true)
String configStr = configObj.toString()
// configObj.put("min_size", 5)
String method = "POST"
Map<String, String> headers = new HashMap<String, String>()
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode)
Map<String, String> querys = new HashMap<String, String>()
// 对图像进行base64编码
String imgBase64 = ""
try {
if(file == null){
file = new File(imgFile)
}
byte[] content = new byte[(int) file.length()]
FileInputStream finputstream = new FileInputStream(file)
finputstream.read(content)
finputstream.close()
imgBase64 = new String(encodeBase64(content))
} catch (IOException e) {
e.printStackTrace()
return null
}
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject()
requestObj.put("image", imgBase64)
if(configStr.length() > 0) {
requestObj.put("configure", configStr)
}
String bodys = requestObj.toString()
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)
int stat = response.getStatusLine().getStatusCode()
if(stat != 200){
log.error("Http code: %s",stat)
log.error("http header error msg: %s",response.getFirstHeader("X-Ca-Error-Message"))
log.error("Http body error msg: %s",EntityUtils.toString(response.getEntity()))
return null
}
String res = EntityUtils.toString(response.getEntity())
JSONObject resObj = JSON.parseObject(res)
JSONObject plates = resObj.getJSONArray("plates").getJSONObject(0)
String aliVehiclePlate = plates.getString("txt")
log.debug("识别车牌号:【%s】 res: %s",aliVehiclePlate,resObj.toJSONString())
return aliVehiclePlate
} catch (Exception e) {
e.printStackTrace()
return null
}
}
```
HttpUtils工具
package com.cowr.hsjygl.aliocr;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}