用百度OCR識別圖片中的文字

一绅喉、邏輯

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;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末元践,一起剝皮案震驚了整個濱河市韭脊,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌单旁,老刑警劉巖沪羔,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡蔫饰,警方通過查閱死者的電腦和手機琅豆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來篓吁,“玉大人茫因,你說我怎么就攤上這事≌燃簦” “怎么了冻押?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長盛嘿。 經(jīng)常有香客問我洛巢,道長,這世上最難降的妖魔是什么次兆? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任稿茉,我火速辦了婚禮,結(jié)果婚禮上类垦,老公的妹妹穿的比我還像新娘狈邑。我一直安慰自己,他們只是感情好蚤认,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布米苹。 她就那樣靜靜地躺著,像睡著了一般砰琢。 火紅的嫁衣襯著肌膚如雪蘸嘶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天陪汽,我揣著相機與錄音训唱,去河邊找鬼。 笑死挚冤,一個胖子當著我的面吹牛况增,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播训挡,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼澳骤,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了澜薄?” 一聲冷哼從身側(cè)響起为肮,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肤京,沒想到半個月后颊艳,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年棋枕,在試婚紗的時候發(fā)現(xiàn)自己被綠了白修。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡戒悠,死狀恐怖熬荆,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情绸狐,我是刑警寧澤卤恳,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站寒矿,受9級特大地震影響突琳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜符相,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一拆融、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧啊终,春花似錦镜豹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至例衍,卻和暖如春昔期,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背佛玄。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工硼一, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人梦抢。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓般贼,卻偏偏與公主長得像,于是被迫代替她去往敵國和親奥吩。 傳聞我的和親對象是個殘疾皇子具伍,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容