用百度OCR识别图片中的文字

一、逻辑

1、在百度智能云-管理中心创建文字识别应用,获得其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 generalBasicOCR(String imageFilePath, String accessToken){
        List 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 words= bean.getWords_result();
            for(int i=0;i

二、不废话,附上源码文件(不知怎么附上文件?),只能把源代码贴上来
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 generalBasicOCR(String imageFilePath, String accessToken){
        List 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 words= bean.getWords_result();
            for(int i=0;i

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 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 getWords_result() {
        return words_result;
    }

    public void setWords_result(List 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发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    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();
            // 设置通用的请求属性
            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> 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("发送GET请求出现异常!" + e);
        } finally {// 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                System.out.println(e2);
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        return sendPost(url, param, null);
    }
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param charset
     *            请求返回的串的字符集
     * @return 所代表远程资源的响应结果
     */
    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();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            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("发送 POST 请求出现异常!" + e);
        } finally {//使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
        return result;
    }

    /**
     * 将字符串转成unicode
     * 
     * @param str
     *            待转字符串
     * @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 decodeURIComponent function. Returns null if the String is null.
     *
     * @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 encodeURIComponent function. Returns null if the String is null.
     * 
     * @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;
    }
}

你可能感兴趣的:(用百度OCR识别图片中的文字)