申请账号,设置应用,获取keyID什么的自己上百度AI官网设置查看,这里直接上代码。
初始化java客户端及获取access_taken
@SuppressWarnings("all")
public class OcrtokenUtil extends BaseController{
//官网获取 App ID
public static final String APP_ID = "11******10";
//官网获取的 API Key
public static final String clientId="INIV6Umw********sKKhaxu";
//官网获取的 Secret Key
public static final String clientSecret="sxg5bAza68*************j8PZB7RGvnz";
//API url
public static final String authHost="https://aip.baidubce.com/oauth/2.0/token";
//grant_type为固定参数
public static final String grantType="client_credentials";
private static final Logger logger = LoggerFactory.getLogger(OcrtokenUtil.class);
/**
* @Title: OcrGetApi
* @Description: 获取access_token get请求
* @return JSONObject 返回类型
* @author wl
* @date 2018年4月17日 上午11:49:09
*/
public static String OcrGetApi()throws Exception {
String access_token =null;
String getAccessTokenUrl = authHost
+ "?grant_type=client_credentials"
+ "&client_id=" + clientId
+ "&client_secret=" + clientSecret;
JSONObject jsonobj=HttpClientUtil.httpGetAndReturn(getAccessTokenUrl);
if (jsonobj == null || jsonobj.isNullObject()){
logger.error("token获取异常");
}else{
access_token = jsonobj.getString("access_token");
logger.info("此次token信息是:"+access_token);
}
return access_token;
}
/**
* @Title: OcrPostApi
* @Description: 获取access_token post请求
* @return JSONObject 返回类型
* @author wl
* @date 2018年4月17日 上午11:49:09
*/
public static String OcrPostApi()throws Exception {
String access_token =null;
Map<String, Object>map=new HashMap<>();
map.put("client_id", clientId);
map.put("client_secret", clientSecret);
map.put("grant_type", grantType);
JSONObject jsonobj=HttpClientUtil.httpPostMap(authHost, map);
if (jsonobj == null || jsonobj.isNullObject()){
logger.error("token获取异常");
}else{
access_token = jsonobj.getString("access_token");
logger.info("此次token信息是:"+access_token);
}
return access_token;
}
/**
* @Title: Ocrinit
* @Description: 文字识别java客户端
* @param @return
* @param @throws Exception 参数说明
* @return AipOcr 返回类型
* @author wl
* @date 2018年4月27日 下午12:09:15
*/
public static AipOcr Ocrinit()throws Exception {
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, clientId, clientSecret);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
// 可选:设置代理服务器地址, http和socket二选一,或者均不设置
/*client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理
*/
// 可选:设置log4j日志输出格式,若不设置,则使用默认配置
// 也可以直接通过jvm启动参数设置此环境变量
System.setProperty("aip.log4j.conf", "log4j.properties");
return client;
}
}
本地图片文字识别实例
@Controller
@SuppressWarnings("all")
public class OcrController extends BaseController{
private static final Logger logger = LoggerFactory.getLogger(OcrController.class);
/**
* @Title: ocrtaken
* @Description: 文字识别taken
* @param @throws Exception 参数说明
* @return void 返回类型
* @author wl
* @date 2018年4月27日 下午1:14:59
*/
@RequestMapping("/public/ocrtaken")
public void ocrtaken(HttpServletRequest request, HttpServletResponse response,Model m)throws Exception {
FinalResult result = new FinalResult();
HttpSession session = request.getSession();
String cookname="accessToken";
try {
String accessToken=(String) session.getAttribute(cookname);
Cookie cookie=CookieUtil.getCookie(request, cookname);
if(cookie==null || StringUtil.isEmpty(accessToken)){
int maxValue=60*60*24*30;
accessToken=OcrtokenUtil.OcrPostApi();
session.setAttribute(cookname, accessToken);
CookieUtil.setCookie(response, cookname, accessToken, maxValue);
}
result.setRetResult(accessToken);
result.setState("SUCCESS");
result.webSuccess();
} catch (Exception e) {
logger.equals(e.getMessage());
e.printStackTrace();
result.setState("ERROR");
result.webFaild();
}
writeJson(response, result);
}
/**
* @Title: OcrCheck
* @Description: 文字识别
* @param @param data
* @param @throws Exception 参数说明
* @return void 返回类型
* @author wl
* @date 2018年4月27日 上午11:59:48
*/
@RequestMapping("/public/OcrCheck")
public void OcrCheck(HttpServletRequest request, HttpServletResponse response,Model m,FormData data)throws Exception {
FinalResult result = new FinalResult();
HashMap<String, String> options = new HashMap<String, String>();
Map<String, Object> resultMap=new HashMap<>();
Map map=HttpClientUtil.getParameterMap(request);
try {
//初始化客户端
AipOcr client=OcrtokenUtil.Ocrinit();
//参数为图片外链
String image ="C:/Users/admin/Desktop/1.jpg";
//String image =imageUtil.GetImageTolocal((String) map.get("imageUrl"));
////------------进行文字识别 -------------////
options.put("language_type", "CHN_ENG");
//高清识别
JSONObject res = client.basicAccurateGeneral(image, options);
//通用识别
//JSONObject res = client.basicGeneral(image, options);
logger.info("文字识别完成");
JSONArray jsonArray=res.getJSONArray("words_result");
System.out.println(jsonArray);
result.setRetResult(jsonArray);
result.setState("SUCCESS");
result.webSuccess();
} catch (Exception e) {
logger.equals(e.getMessage());
e.printStackTrace();
result.setState("ERROR");
result.webFaild();
}
writeJson(response, result);
}
}