基於百度 AI 文字識別解析二維碼
本章主要介紹百度 AI 開放平臺提供的 SDK 來解析二維碼。
目前現有的免費解析二維碼的 API 存在瓶頸,必須精確到一定的寬度和清晰度才能解析,不符合現實生活中使用。通過第三方 AI 方式解析二維碼,可以避免
這些問題,也符合使用習慣,與微信掃碼解析一樣方便快速。
以下代碼在百度提供的代碼基礎上,進行了一些優化,更加方便
比如:定時獲取 access token,通過文件流傳入文件
代碼示例:
package com.jacky.utils.qrcode.baidu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import com.jacky.utils.StringUtil;
public class BaiduQrCodeUtil {
public static void main(String[] args) throws Exception {
String filePath = "C:\\Users\\Jacky\\Desktop\\4png.png";
String text = doQRCode(filePath);
System.out.println(text);
}
private static final String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode";// 請求url
private static final String clientId = "";// 官網獲取的 API Key 更新爲你註冊的
private static final String clientSecret = "";// 官網獲取的 Secret Key 更新爲你註冊的
private static String accessToken;
public static String doQRCode(InputStream inputStream) {
if (StringUtil.isBlank(accessToken)) {
accessToken = getAuth();
}
String text = null;
String result = null;
try {
byte[] imgData = FileUtil.readFileByInputStream(inputStream);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param = "image=" + imgParam;
result = HttpUtil.post(url, accessToken, param);
System.out.println(result);
JSONObject json = new JSONObject(result);
JSONArray array = json.getJSONArray("codes_result");
if (array != null && array.length() > 0) {
JSONArray textArray = new JSONObject(array.get(0).toString()).getJSONArray("text");
if (textArray != null && textArray.length() > 0) {
text = textArray.getString(0);
}
}
} catch (Exception e) {
try {
JSONObject json = new JSONObject(result);
text = json.getString("error_msg");
} catch (Exception e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return text;
}
/**
* 重要提示代碼中所需工具類
* FileUtil,Base64Util,HttpUtil,GsonUtils請從
* https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
* https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
* https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
* https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
* 下載
*/
public static String doQRCode(String filePath) {
String text = null;
try {
// 本地文件路徑
// String filePath = "C:\\Users\\Jacky\\Desktop\\4png.png";
// byte[] imgData = FileUtil.readFileByBytes(filePath);
byte[] imgData = FileUtil.readFileByInputStream(new FileInputStream(new File(filePath)));
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param = "image=" + imgParam;
String result = HttpUtil.post(url, accessToken, param);
// System.out.println(result);
JSONObject json = new JSONObject(result);
JSONArray array = json.getJSONArray("codes_result");
if (array != null && array.length() > 0) {
JSONArray textArray = new JSONObject(array.get(0).toString()).getJSONArray("text");
if (textArray != null && textArray.length() > 0) {
text = textArray.getString(0);
}
}
return text;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 獲取權限token
* @return 返回示例:
* {
* "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
* "expires_in": 2592000
* }
*/
public static String getAuth() {
return getAuth(clientId, clientSecret);
}
/**
* 獲取API訪問token
* 該token有一定的有效期,需要自行管理,當失效時需重新獲取.
* @param ak - 百度雲官網獲取的 API Key
* @param sk - 百度雲官網獲取的 Securet Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
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();
connection.setRequestMethod("GET");
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
// for (String key : map.keySet()) {
// System.err.println(key + "--->" + map.get(key));
// }
// 定義 BufferedReader輸入流來讀取URL的響應
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回結果示例
*/
// System.err.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;
}
@PostConstruct
public void init() {
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(()->{
accessToken = "24.64a89fecddc3aa8f8dd19dbed62027eb.2592000.1630582423.282335-24645224";//getAuth();
}, 0, 29, TimeUnit.DAYS);
}
}
輔助工具類:百度提供的鏈接也可以下載到
package com.jacky.utils.qrcode.baidu;
/**
* Base64 工具類
*/
public class Base64Util {
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
public Base64Util() {
}
public static String encode(byte[] from) {
StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
int num = 0;
char currentByte = 0;
int i;
for (i = 0; i < from.length; ++i) {
for (num %= 8; num < 8; num += 6) {
switch (num) {
case 0:
currentByte = (char) (from[i] & lead6byte);
currentByte = (char) (currentByte >>> 2);
case 1:
case 3:
case 5:
default:
break;
case 2:
currentByte = (char) (from[i] & last6byte);
break;
case 4:
currentByte = (char) (from[i] & last4byte);
currentByte = (char) (currentByte << 2);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
}
break;
case 6:
currentByte = (char) (from[i] & last2byte);
currentByte = (char) (currentByte << 4);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
}
}
to.append(encodeTable[currentByte]);
}
}
if (to.length() % 4 != 0) {
for (i = 4 - to.length() % 4; i > 0; --i) {
to.append("=");
}
}
return to.toString();
}
}
package com.jacky.utils.qrcode.baidu;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* 文件讀取工具類
*/
public class FileUtil {
/**
* 讀取文件內容,作爲字符串返回
*/
public static String readFileAsString(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
if (file.length() > 1024 * 1024 * 1024) {
throw new IOException("File is too large");
}
StringBuilder sb = new StringBuilder((int) (file.length()));
// 創建字節輸入流
FileInputStream fis = new FileInputStream(filePath);
// 創建一個長度爲10240的Buffer
byte[] bbuf = new byte[10240];
// 用於保存實際讀取的字節數
int hasRead = 0;
while ( (hasRead = fis.read(bbuf)) > 0 ) {
sb.append(new String(bbuf, 0, hasRead));
}
fis.close();
return sb.toString();
}
/**
* 根據文件路徑讀取byte[] 數組
*/
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
short bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len1;
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
bos.write(buffer, 0, len1);
}
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
public static byte[] readFileByInputStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*1024);
BufferedInputStream in = null;
try {
in = new BufferedInputStream(inputStream);
short bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len1;
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
bos.write(buffer, 0, len1);
}
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
/*
* Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
*/
package com.jacky.utils.qrcode.baidu;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Json工具類.
*/
public class GsonUtils {
private static Gson gson = new GsonBuilder().create();
public static String toJson(Object value) {
return gson.toJson(value);
}
public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
return gson.fromJson(json, classOfT);
}
public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
return (T) gson.fromJson(json, typeOfT);
}
}
package com.jacky.utils.qrcode.baidu;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* http 工具類
*/
public class HttpUtil {
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtil.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 打開和URL之間的連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 設置通用的請求屬性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到請求的輸出流對象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍歷所有的響應頭字段
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
相關產品鏈接:https://ai.baidu.com/tech/ocr_others/qrcode
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/uKj2uDbIVshl1zqdMcAlkw