一绅喉、邏輯
1、在百度智能云-管理中心創(chuàng)建文字識別應用叫乌,獲得其API Key和Secret Key柴罐;
2、通過一個http請求獲取AccessToken:
/**
* 獲取百度智能云/文字識別的AccessToken
*
* @param apiKey
* 百度智能云/文字識別的API Key
* @param secretKey
* 百度智能云/文字識別的Secret Key
* @return 百度智能云/文字識別的AccessToken
*/
public static String getOCRAccessToken(String apiKey, String secretKey) {
String url="https://aip.baidubce.com/oauth/2.0/token";
String param="grant_type=client_credentials"
// 2. 百度智能云/文字識別的API Key
+ "&client_id="+apiKey
// 3. 百度智能云/文字識別的Secret Key
+ "&client_secret="+secretKey;
String result= HttpRequestUtils.sendGet(url,param);
if(result!=null&&!result.isEmpty()){
AccessTokenBean bean = new Gson().fromJson(result, AccessTokenBean.class);
String accessToken=bean.getAccess_token();
return accessToken;
}
return null;
}
3憨奸、通過http請求革屠,返回識別的文字:
/**
* 百度智能云/文字識別的通用文字識別
*
* @param imageFilePath
* 圖片文件路徑
* @param accessToken
* 百度智能云/文字識別的AccessToken
* @return 百度智能云/文字識別的通用文字識別到的圖片中的文字
*/
public static List<String> generalBasicOCR(String imageFilePath, String accessToken){
List<String> retWords=new ArrayList<>();
String imageBase64=ImageUtils.imageToBase64String(imageFilePath);
if(imageBase64==null||imageBase64.isEmpty()) {
return retWords;
}
String url="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+accessToken;
String param="image="+HttpRequestUtils.encodeURIComponent(imageBase64);
String result=HttpRequestUtils.sendPost(url,param);
if(result!=null&&!result.isEmpty()){
OCRResultBean bean = new Gson().fromJson(result, OCRResultBean.class);
List<OCRResultBean.WordsBean> words= bean.getWords_result();
for(int i=0;i<words.size();i++){
String word=words.get(i).getWords();
retWords.add(word);
}
}
return retWords;
}
二、不廢話排宰,附上源碼文件(不知怎么附上文件似芝?),只能把源代碼貼上來
1板甘、BaiduOcrUtils
package yxc.common.ocr;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import yxc.common.http.HttpRequestUtils;
import yxc.common.image.ImageUtils;
public final class BaiduOcrUtils {
private BaiduOcrUtils() {
super();
}
/**
* 獲取百度智能云/文字識別的AccessToken
*
* @param apiKey
* 百度智能云/文字識別的API Key
* @param secretKey
* 百度智能云/文字識別的Secret Key
* @return 百度智能云/文字識別的AccessToken
*/
public static String getOCRAccessToken(String apiKey, String secretKey) {
String url="https://aip.baidubce.com/oauth/2.0/token";
String param="grant_type=client_credentials"
// 2. 百度智能云/文字識別的API Key
+ "&client_id="+apiKey
// 3. 百度智能云/文字識別的Secret Key
+ "&client_secret="+secretKey;
String result= HttpRequestUtils.sendGet(url,param);
if(result!=null&&!result.isEmpty()){
AccessTokenBean bean = new Gson().fromJson(result, AccessTokenBean.class);
String accessToken=bean.getAccess_token();
return accessToken;
}
return null;
}
/**
* 百度智能云/文字識別的通用文字識別
*
* @param imageFilePath
* 圖片文件路徑
* @param accessToken
* 百度智能云/文字識別的AccessToken
* @return 百度智能云/文字識別的通用文字識別到的圖片中的文字
*/
public static List<String> generalBasicOCR(String imageFilePath, String accessToken){
List<String> retWords=new ArrayList<>();
String imageBase64=ImageUtils.imageToBase64String(imageFilePath);
if(imageBase64==null||imageBase64.isEmpty()) {
return retWords;
}
String url="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+accessToken;
String param="image="+HttpRequestUtils.encodeURIComponent(imageBase64);
String result=HttpRequestUtils.sendPost(url,param);
if(result!=null&&!result.isEmpty()){
OCRResultBean bean = new Gson().fromJson(result, OCRResultBean.class);
List<OCRResultBean.WordsBean> words= bean.getWords_result();
for(int i=0;i<words.size();i++){
String word=words.get(i).getWords();
retWords.add(word);
}
}
return retWords;
}
}
2党瓮、AccessTokenBean
package yxc.common.ocr;
public class AccessTokenBean {
private String refresh_token;
private int expires_in;
private String scope;
private String session_key;
private String access_token;
private String session_secret;
public AccessTokenBean() {
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getSession_secret() {
return session_secret;
}
public void setSession_secret(String session_secret) {
this.session_secret = session_secret;
}
}
3、OCRResultBean
package yxc.common.ocr;
import java.util.List;
public class OCRResultBean {
private long log_id;
private int words_result_num;
private List<WordsBean> words_result;
public long getLog_id() {
return log_id;
}
public void setLog_id(long log_id) {
this.log_id = log_id;
}
public int getWords_result_num() {
return words_result_num;
}
public void setWords_result_num(int words_result_num) {
this.words_result_num = words_result_num;
}
public List<WordsBean> getWords_result() {
return words_result;
}
public void setWords_result(List<WordsBean> words_result) {
this.words_result = words_result;
}
public static class WordsBean {
private String words;
public String getWords() {
return words;
}
public void setWords(String words) {
this.words = words;
}
}
}
4盐类、ImageUtils
package yxc.common.image;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.axis.encoding.Base64;
public final class ImageUtils {
private ImageUtils() {
super();
}
public static String imageToBase64String(String filePath) {
File imageFile=new File(filePath);
if(!imageFile.exists()) {
return null;
}
try {
Image image = ImageIO.read(imageFile);
if(image!=null) {
return imageToBase64String(image);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String imageToBase64String(Image image) {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
try {
ImageIO.write((BufferedImage)image, "JPG", baos);
byte[] imageBytes=baos.toByteArray();
String base64String=Base64.encode(imageBytes);
baos.close();
return base64String;
} catch (IOException e) {
e.printStackTrace();
}finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return "";
}
}
5寞奸、HttpRequestUtils
package yxc.common.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
public final class HttpRequestUtils {
private HttpRequestUtils() {
super();
}
/**
* 向指定URL發(fā)送GET方法的請求
*
* @param url
* 發(fā)送請求的URL
* @param param
* 請求參數(shù),請求參數(shù)應該是 name1=value1&name2=value2 的形式在跳。
* @return URL 所代表遠程資源的響應結(jié)果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設(shè)置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
/*for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}*/
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發(fā)送GET請求出現(xiàn)異常蝇闭!" + e);
} finally {// 使用finally塊來關(guān)閉輸入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
System.out.println(e2);
}
}
return result;
}
/**
* 向指定 URL 發(fā)送POST方法的請求
*
* @param url
* 發(fā)送請求的 URL
* @param param
* 請求參數(shù),請求參數(shù)應該是 name1=value1&name2=value2 的形式硬毕。
* @return 所代表遠程資源的響應結(jié)果
*/
public static String sendPost(String url, String param) {
return sendPost(url, param, null);
}
/**
* 向指定 URL 發(fā)送POST方法的請求
*
* @param url
* 發(fā)送請求的 URL
* @param param
* 請求參數(shù),請求參數(shù)應該是 name1=value1&name2=value2 的形式礼仗。
* @param charset
* 請求返回的串的字符集
* @return 所代表遠程資源的響應結(jié)果
*/
public static String sendPost(String url, String param, String charset) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(shè)置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發(fā)送POST請求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發(fā)送請求參數(shù)
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
if(charset==null||charset.isEmpty()) {
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
}
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發(fā)送 POST 請求出現(xiàn)異常吐咳!" + e);
} finally {//使用finally塊來關(guān)閉輸出流、輸入流
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
System.out.println(ex);
}
}
return result;
}
/**
* 將字符串轉(zhuǎn)成unicode
*
* @param str
* 待轉(zhuǎn)字符串
* @return unicode字符串
*/
public static String convert(String str) {
if (str == null) {
str = "";
}
String tmp;
StringBuffer sb = new StringBuffer(1000);
char c;
int i, j;
sb.setLength(0);
for (i = 0; i < str.length(); i++) {
c = str.charAt(i);
sb.append("%u");
j = (c >>> 8); //取出高8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
j = (c & 0xFF); //取出低8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
}
return (new String(sb));
}
/**
* Decodes the passed UTF-8 String using an algorithm that's compatible with JavaScript's <code>decodeURIComponent</code> function. Returns <code>null</code> if the String is <code>null</code>.
*
* @param s
* The UTF-8 encoded String to be decoded
* @return the decoded String
*/
public static String decodeURIComponent(String s) {
if (s == null) {
return null;
}
String result = null;
try {
result = URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {// This exception should never occur.
result = s;
}
return result;
}
/**
* Encodes the passed String as UTF-8 using an algorithm that's compatible with JavaScript's <code>encodeURIComponent</code> function. Returns <code>null</code> if the String is <code>null</code>.
*
* @param s
* The String to be encoded
* @return the encoded String
*/
public static String encodeURIComponent(String s) {
String result = null;
try {
result = URLEncoder.encode(s, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {// This exception should never occur.
result = s;
}
return result;
}
}