【百度OCR 集成篇】java后台之使用SDK集成

全部代码下载地址:https://download.csdn.net/download/qq_33333654/11914449

maven:


  com.baidu.aip
  java-sdk
  4.12.0

 

AipOcr对象单例:
public class AipOcrSingleton {
    public static volatile AipOcr aipOcr = null;
    //设置APPID/AK/SK
    public static final String APP_ID = "";
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";
    public static final int CONNECTION_TIME_OUT = 2000;//建立连接的超时时间(单位:毫秒)
    public static final int SOCKET_TIME_OUT = 6000;//通过打开的连接传输数据的超时时间(单位:毫秒)
    private AipOcrSingleton(){}

    public static AipOcr getAipOcr(){
        if(aipOcr == null){
            synchronized (AipOcrSingleton.class){
                if(aipOcr == null){
                    aipOcr = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
                    // 可选:设置网络连接参数
                    aipOcr.setConnectionTimeoutInMillis(CONNECTION_TIME_OUT);
                    aipOcr.setSocketTimeoutInMillis(SOCKET_TIME_OUT);
                    //setHttpProxy 设置http代理服务器
                    //setSocketProxy 设置socket代理服务器 (http和socket类型代理服务器只能二选一)
                }
            }
        }
        return aipOcr;
    }
}

 测试:

 @Test
    public void testAipOcr(){ //通用文字识别
        // 初始化一个AipOcr
        AipOcr client = AipOcrSingleton.getAipOcr();
        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 传入可选参数调用接口
        HashMap options = new HashMap();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        // 调用接口
       /* String path = "C:\\Users\\Administrator\\Desktop\\IMG_0403.JPG";
        JSONObject res = client.basicGeneral(path, options);
        System.out.println(res.toString(2));*/

       /* // 参数为二进制数组
        byte[] file = readFile("test.jpg");
        res = client.basicGeneral(file, options);
        System.out.println(res.toString(2));
*/
        // 通用文字识别, 图片参数为远程url图片
        String url = "https://timgsa.baidu.com/timg?image&quality=80&size=&sec=1571819553651&di=db2f26a724a259fb93c89964b2ea9cc7&imgtype=0&src=http%3A%2F%2Fwww.ansunspd.com%2Fuploads%2Fallimg%2F110617%2F1_110617115131_1.jpg";
        JSONObject res = client.basicGeneralUrl(url, options);
        System.out.println(res.toString(2));
    }

你可能感兴趣的:(百度ocr)