基于SpringBoot调用百度ocr实现图片的文字识别功能

基于SpringBoot调用百度ocr实现图片的文字识别功能

      • 1、导入坐标
      • 2、DTO实体类
      • 3、Controller层接口
      • 4、相关的工具类
        • 4.1 将本地图片进行Base64位编码的工具类
        • 4.2 BaiDuOCR的工具类

1、导入坐标

       <!--百度文字识别接口-->
        <dependency>
            <groupId>com.baidu.aip</groupId>
            <artifactId>java-sdk</artifactId>
            <version>4.3.2</version>
        </dependency>

2、DTO实体类

import lombok.Data;

@Data
public class CidDTO {
     
    //身份证姓名
    private String name;
    //民族
    private String nation;
    //出生日期
    private String birthday;
    //地址
    private String address;
    //身份证号
    private String cid;
    //性别
    private String sex;
}

3、Controller层接口

    /**
     * 身份证信息识别
     * @return
     */
    @GetMapping("cid")
    public CidDTO cid(){
     
            //获取本地的绝对路径图片(实际工程传入的是用户上传的图片)
            File file = new File("D:\\2.jpg");
            //进行BASE64位编码
            String imageBase = BASE64.encodeImgageToBase64(file);
            imageBase = imageBase.replaceAll("\r\n", "");
            imageBase = imageBase.replaceAll("\\+", "%2B");
            //百度云的文字识别接口,后面参数为获取到的token
            String httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="+BaiDuOCR.getAuth();
            //id_card_side=front 识别正面    id_card_side=back  识别背面
            String httpArg = "detect_direction=true&id_card_side=front&image=" + imageBase;
            String jsonResult = BaiDuOCR.request(httpUrl, httpArg);
            System.out.println("返回的结果--------->" + jsonResult);
            HashMap<String, String> map = BaiDuOCR.getHashMapByJson(jsonResult);
            CidDTO cidDTO = new CidDTO();
            cidDTO.setName(map.get("姓名"));
            cidDTO.setNation(map.get("民族"));
            cidDTO.setBirthday(map.get("出生日期"));
            cidDTO.setAddress(map.get("住址"));
            cidDTO.setCid(map.get("公民身份号码"));
            cidDTO.setSex(map.get("性别"));
            return cidDTO;
         }

4、相关的工具类

4.1 将本地图片进行Base64位编码的工具类

import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class BASE64 {
     

/**
 * 将本地图片进行Base64位编码
 * 

* imgUrl 图片的url路径,如e:\\123.png * * @return */ public static String encodeImgageToBase64(File imageFile) { // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 // 其进行Base64编码处理 byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(imageFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (Exception e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64编码过的字节数组字符串 return encoder.encode(data); } }

4.2 BaiDuOCR的工具类

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class BaiDuOCR {
     
    public static String getAuth() {
     
        // 官网获取的 API Key
        String clientId = "kNCQikv8oTBWvQhtIBF7v7ep";
        // 官网获取的 Secret Key
        String clientSecret = "5Yo8Bt9X0U2NDI9i97uXVK7wxWXTKTpx";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取token
     * @param ak
     * @param sk
     * @return
     */
    public static String getAuth(String ak, String sk) {
     
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
     
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            //百度推荐使用POST请求
            connection.setRequestMethod("POST");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
     
                result += line;
            }
            //System.out.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
     
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }


    /**
     * 调用OCR
     * @param httpUrl
     * @param httpArg
     * @return
     */
    public static String request(String httpUrl, String httpArg) {
     
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        try {
     
            //用java JDK自带的URL去请求
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            //设置该请求的消息头
            //设置HTTP方法:POST
            connection.setRequestMethod("POST");
            //设置其Header的Content-Type参数为application/x-www-form-urlencoded
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", "kNCQikv8oTBWvQhtIBF7v7ep");
            //将第二步获取到的token填入到HTTP header
            connection.setRequestProperty("access_token", BaiDuOCR.getAuth());
            connection.setDoOutput(true);
            connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
     
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return result;
    }

    /**
     *身份证参数转换
     * @param jsonResult
     * @return
     */
    public static HashMap<String, String> getHashMapByJson(String jsonResult) {
     
        HashMap map = new HashMap<String, String>();
        try {
     
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONObject words_result = jsonObject.getJSONObject("words_result");
            Iterator<String> it = words_result.keys();
            while (it.hasNext()) {
     
                String key = it.next();
                JSONObject result = words_result.getJSONObject(key);
                String value = result.getString("words");
                switch (key) {
     
                    case "姓名":
                        map.put("姓名", value);
                        break;
                    case "民族":
                        map.put("民族", value);
                        break;
                    case "住址":
                        map.put("住址", value);
                        break;
                    case "公民身份号码":
                        map.put("公民身份号码", value);
                        break;
                    case "出生":
                        map.put("出生日期", value);
                        break;
                    case "性别":
                        map.put("性别", value);
                        break;
                    case "失效日期":
                        map.put("失效日期", value);
                        break;
                    case "签发日期":
                        map.put("签发日期", value);
                        break;
                    case "签发机关":
                        map.put("签发机关", value);
                        break;
                }
            }
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 营业执照参数转换
     * @param jsonResult
     * @return
     */
    public static HashMap<String, String> getBusniessLicHashMap(String jsonResult){
     
        HashMap map = new HashMap<String, String>();
        try {
     
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONObject words_result = jsonObject.getJSONObject("words_result");
            Iterator<String> it = words_result.keys();
            while (it.hasNext()) {
     
                String key = it.next();
                JSONObject result = words_result.getJSONObject(key);
                String value = result.getString("words");
                switch (key) {
     
                    case "单位名称":
                        map.put("单位名称", value);
                        break;
                    case "类型":
                        map.put("类型", value);
                        break;
                    case "法人":
                        map.put("法人", value);
                        break;
                    case "地址":
                        map.put("地址", value);
                        break;
                    case "有效期":
                        map.put("有效期", value);
                        break;
                    case "性别":
                        map.put("性别", value);
                        break;
                    case "证件编号":
                        map.put("证件编号", value);
                        break;
                    case "签发日期":
                        map.put("签发日期", value);
                        break;
                    case "社会信用代码":
                        map.put("社会信用代码", value);
                        break;
                }
            }
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return map;
    }

}

你可能感兴趣的:(springboot,java,json)