调用腾讯优图OCR手写体文字识别接口

时间:2024-05-23 15:11:15

一、百度搜索:腾讯优图·AI开放平台;

二、点击技术体验中心,可以体验一下效果;

三、点击开发者中心,左侧找到“API文档”里面的“通用手写体文字识别”。这里面有个“鉴权签名方法”的链接,点击进去按照步骤一步步来生成鉴权签名。首先登录open.youtu.qq.com,按照要求做就能获取AppID、SecretID和SecretKey;

四、新建一个Youtu.java,然后复制下面代码进去:

package com.youtu;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import com.youtu.sign.*;
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Youtu {

    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public final static  String API_YOUTU_END_POINT = "https://api.youtu.qq.com/youtu/";
    public final static  String API_YOUTU_CHARGE_END_POINT = "https://vip-api.youtu.qq.com/youtu/";

    // 30 days
    private static int EXPIRED_SECONDS = 2592000;
    private String m_appid;
    private String m_secret_id;
    private String m_secret_key;
    private String m_end_point;
    private String m_user_id;
    private boolean m_not_use_https;

    /**
     * PicCloud 构造方法
     *
     * @param appid
     *            授权appid
     * @param secret_id
     *            授权secret_id
     * @param secret_key
     *            授权secret_key
     */
    public Youtu(String appid, String secret_id, String secret_key,String end_point,String user_id) {
        m_appid = appid;
        m_secret_id = secret_id;
        m_secret_key = secret_key;
        m_end_point=end_point;
        m_user_id=user_id;
        m_not_use_https=!end_point.startsWith("https");
    }

    public String StatusText(int status) {

        String statusText = "UNKOWN";

        switch (status)
        {
            case 0:
                statusText = "CONNECT_FAIL";
                break;
            case 200:
                statusText = "HTTP OK";
                break;
            case 400:
                statusText = "BAD_REQUEST";
                break;
            case 401:
                statusText = "UNAUTHORIZED";
                break;
            case 403:
                statusText = "FORBIDDEN";
                break;
            case 404:
                statusText = "NOTFOUND";
                break;
            case 411:
                statusText = "REQ_NOLENGTH";
                break;
            case 423:
                statusText = "SERVER_NOTFOUND";
                break;
            case 424:
                statusText = "METHOD_NOTFOUND";
                break;
            case 425:
                statusText = "REQUEST_OVERFLOW";
                break;
            case 500:
                statusText = "INTERNAL_SERVER_ERROR";
                break;
            case 503:
                statusText = "SERVICE_UNAVAILABLE";
                break;
            case 504:
                statusText = "GATEWAY_TIME_OUT";
                break;
        }
        return statusText;
    }


    private void GetBase64FromFile(String filePath, StringBuffer base64)
    throws IOException {
        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            InputStream in = new FileInputStream(imageFile);
            byte data[] = new byte[(int) imageFile.length()]; // 创建合适文件大小的数组
            in.read(data); // 读取文件中的内容到b[]数组
            in.close();
            base64.append(Base64Util.encode(data));

        } else {
            throw new FileNotFoundException(filePath + " not exist");
        }

    }

    private JSONObject SendHttpRequest(JSONObject postData, String mothod)
    throws IOException, JSONException, KeyManagementException, NoSuchAlgorithmException {

        StringBuffer mySign = new StringBuffer("");
        YoutuSign.appSign(m_appid, m_secret_id, m_secret_key,
            System.currentTimeMillis() / 1000 + EXPIRED_SECONDS,
            m_user_id, mySign);

        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
        System.setProperty("sun.net.client.defaultReadTimeout", "30000");
        URL url = new URL(m_end_point + mothod);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // set header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("user-agent", "youtu-java-sdk");
        connection.setRequestProperty("Authorization", mySign.toString());

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "text/json");
        connection.connect();

        // POST请求
        DataOutputStream out = new DataOutputStream(
            connection.getOutputStream());

        postData.put("app_id", m_appid);
        out.write(postData.toString().getBytes("utf-8"));
        //out.writeBytes(postData.toString());
        out.flush();
        out.close();
        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(
            connection.getInputStream()));
        String lines;
        StringBuffer resposeBuffer = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            resposeBuffer.append(lines);
        }
        // System.out.println(resposeBuffer+"\n");
        reader.close();
        // 断开连接
        connection.disconnect();

        JSONObject respose = new JSONObject(resposeBuffer.toString());

        return respose;

    }


    private  JSONObject SendHttpsRequest(JSONObject postData,String mothod)
    throws NoSuchAlgorithmException, KeyManagementException,
    IOException, JSONException {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
            new java.security.SecureRandom());

        StringBuffer mySign = new StringBuffer("");
        YoutuSign.appSign(m_appid, m_secret_id, m_secret_key,
            System.currentTimeMillis() / 1000 + EXPIRED_SECONDS,
            m_user_id, mySign);

        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
        System.setProperty("sun.net.client.defaultReadTimeout", "30000");

        URL url = new URL(m_end_point + mothod);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
     // set header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("user-agent", "youtu-java-sdk");
        connection.setRequestProperty("Authorization", mySign.toString());

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "text/json");
        connection.connect();

        // POST请求
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        postData.put("app_id", m_appid);
        out.write(postData.toString().getBytes("utf-8"));
        // 刷新、关闭
        out.flush();
        out.close();

        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        StringBuffer resposeBuffer = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            resposeBuffer.append(lines);
        }
         // System.out.println(resposeBuffer+"\n");
        reader.close();
         // 断开连接
        connection.disconnect();

        JSONObject respose = new JSONObject(resposeBuffer.toString());

        return respose;
    }
    /**
     * 识别手写签名
     * @param image_path
     * @return
     * @throws IOException
     * @throws JSONException
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException
     */
    public JSONObject PlateOcr2(String image_path) throws IOException,
    JSONException, KeyManagementException, NoSuchAlgorithmException {
        JSONObject data = new JSONObject();
        
        StringBuffer image_data = new StringBuffer("");
        GetBase64FromFile(image_path, image_data);
        
        data.put("image", image_data);
        
        JSONObject response = m_not_use_https ? SendHttpRequest(data, "ocrapi/handwritingocr") : SendHttpsRequest(data, "ocrapi/handwritingocr");
        
        return response;
    }
    
    public JSONObject PlateOcrUrl2(String image_url) throws IOException,
    JSONException, KeyManagementException, NoSuchAlgorithmException {
        JSONObject data = new JSONObject();
        
        data.put("url", image_url);
        
        JSONObject response = m_not_use_https ? SendHttpRequest(data, "ocrapi/handwritingocr") : SendHttpsRequest(data, "ocrapi/handwritingocr");
        
        return response;
    }
    /**
     * 身份证识别
     */
    public JSONObject IdCardOcr(String image_path,int card_type) throws IOException,
    JSONException, KeyManagementException, NoSuchAlgorithmException {
        StringBuffer image_data = new StringBuffer("");
        JSONObject data = new JSONObject();

        GetBase64FromFile(image_path, image_data);
        data.put("image", image_data.toString());
        data.put("card_type", card_type);
        JSONObject respose =m_not_use_https?SendHttpRequest(data, "ocrapi/idcardocr"):SendHttpsRequest(data, "ocrapi/idcardocr");
        return respose;
    }

    public JSONObject IdCardOcrUrl(String url,int card_type) throws IOException,
    JSONException, KeyManagementException, NoSuchAlgorithmException {
        JSONObject data = new JSONObject();
        data.put("url", url);
        data.put("card_type", card_type);
        JSONObject respose =m_not_use_https?SendHttpRequest(data, "ocrapi/idcardocr"):SendHttpsRequest(data, "ocrapi/idcardocr");
        return respose;
    }
}
五、直接new 这个实例就可以调用了;

六、要识别的签字图片别忘了改变一下文字和纸张的比例,我试了好久找到一个识别率最高的比例:

调用腾讯优图OCR手写体文字识别接口

七、压缩原有图片并将它附着在新的空白底页的方法:

public static final String overlapImage(String bigPath, String smallPath) {
        try {
            BufferedImage big = ImageIO.read(new File(bigPath));
            BufferedImage small = ImageIO.read(new File(smallPath));
            Graphics2D g = big.createGraphics();
            int x = (big.getWidth() - small.getWidth()) / 26;
            int y = (big.getHeight() - small.getHeight()) / 18;
            g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
            g.dispose();
            ImageIO.write(big, "jpg", new File(smallPath));
            return smallPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }