Java 百度OCR 身份证识别

   // Access_Token获取
	private static final String ACCESS_TOKEN_HOST = "https://aip.baidubce.com/oauth/2.0/token?";
	// 身份证识别请求URL
	private static final String OCR_HOST = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?";
	// apiKey,secretKey
    // 自己去百度云申请吧 这里就隐藏了
	private static final String API_KEY = "xxx";
    // 自己去百度云申请吧 这里就隐藏了
	private static final String SECRET_KEY = "xxx";

	// 获取百度云OCR的授权access_token
	public static String getAccessToken() {
		return getAccessToken(API_KEY, SECRET_KEY);
	}

	/**
	 * 获取百度云OCR的授权access_token
	 * 
	 * @param apiKey
	 * @param secretKey
	 * @return
	 */
	public static String getAccessToken(String apiKey, String secretKey) {
		String accessTokenURL = ACCESS_TOKEN_HOST
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 官网获取的 API Key
				+ "&client_id=" + apiKey
				// 3. 官网获取的 Secret Key
				+ "&client_secret=" + secretKey;

		try {
			URL url = new URL(accessTokenURL);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();

			// 获取响应头
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
//			for (String key : map.keySet()) {
//				System.out.println(key + "---->" + map.get(key));
//			}

			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder result = new StringBuilder();
			String inputLine;
			while ((inputLine = bufferedReader.readLine()) != null) {
				result.append(inputLine);
			}
			JSONObject jsonObject = JSONObject.parseObject(result.toString());
			return jsonObject.getString("access_token");

		} catch (Exception e) {
			e.printStackTrace();
			System.err.print("获取access_token失败");
		}
		return null;
	}

	/**
	 * 获取身份证识别后的数据
	 * 
	 * @param imageUrl
	 * @param idCardSide
	 * @return
	 */
	public static String getStringIdentityCard(String imageUrl, String idCardSide) {
		// 身份证OCR的http URL+鉴权token
		String OCRUrl = OCR_HOST + "access_token=" + getAccessToken();
		System.out.println(OCRUrl);
		System.out.println("***************************************************");
		System.out.println(getAccessToken());
		// 对图片进行base64处理
		String image = encodeImageToBase64(imageUrl);
		// 请求参数
		String requestParam = "detect_direction=true&id_card_side=front" + "&image=" + image;

		try {
			// 请求OCR地址
			URL url = new URL(OCRUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// 设置请求方法为POST
			connection.setRequestMethod("POST");

			// 设置请求头
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("apiKey", API_KEY);
			connection.setDoOutput(true);
			connection.getOutputStream().write(requestParam.getBytes(StandardCharsets.UTF_8));
			connection.connect();

			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
			StringBuilder result = new StringBuilder();
			String inputLine;
			while ((inputLine = bufferedReader.readLine()) != null) {
				result.append(inputLine);
			}
			bufferedReader.close();
			return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("身份证OCR识别异常");
			return null;
		}
	}

	/**
	 * 对图片url进行Base64编码处理
	 * 
	 * @param imageUrl
	 * @return
	 */
	public static String encodeImageToBase64(String imageUrl) {
		byte[] data = null;
		try {
//			InputStream inputStream = getUrlFile(new URL(imageUrl)) ;
			InputStream inputStream = new FileInputStream(imageUrl) ;
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();

			// 对字节数组Base64编码
			return URLEncoder.encode(Base64.encode(data),"utf-8");
//			return Base64.encode(data);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static  InputStream getUrlFile(URL url) {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			httpURLConnection = (HttpURLConnection) url.openConnection();
			// 设置网络连接超时时间
			httpURLConnection.setConnectTimeout(3000);
			// 设置应用程序要从网络连接读取数据
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("GET");
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {
				// 从服务器返回一个输入流
				inputStream = httpURLConnection.getInputStream();
			}
		} catch (MalformedURLException e) {
		} catch (IOException e) {

		}
		return inputStream;
	}

	public static void main(String[] args) {

		System.out.println(
				getStringIdentityCard("C:\\Users\\zzf\\Pictures\\1.jpg",
						"C:\\Users\\zzf\\Pictures\\1.jpg"));
		;
	}

主要需要说的就是

  1. image需要urlencode
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值