背景:
日常个人学习或者公司业务中,需要将书籍或者纸质文件转换成电子文稿,最近刚刚做完这一功能,在这里分享给大家
由于本人主要是做后台数据开发,所以主要讲解后台代码,如有不足,还请多喷
首先,在文字识别这一块,百度是做的比较好的,我们就以他为例,每天可以免费使用500次,作为普通人的日常使用,足矣。如果你是企业使用,那就乖乖给钱吧
步骤一:到百度云申请AppID 以及secret id,如有不会,请自行摆渡哈
步骤二:再根据获得的appID 以及secret id,获得token,代码如下:
import org.json.JSONObject;
import JAVA.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/** * 获取token类 */public class AuthService {
public static void main(String[] args) {
getAuth();
}
/** * 获取权限token * @return 返回示例: * { * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567", * "expires_in": 2592000 * } */ public static String getAuth() {
// 官网获取的 API Key 更新为你注册的 String clientId = "KxiVCwBc7T9UU9C9p8qSNqlb";
// 官网获取的 Secret Key 更新为你注册的 String clientSecret = "WcT9Zx5G5XFZ5GyRvuLGZ0nmEfRf5pzp";
return getAuth(clientId, clientSecret);
}
/** * 获取API访问token * 该token有一定的有效期,需要自行管理,当失效时需重新获取. * @param ak - 百度云官网获取的 API Key * @param sk - 百度云官网获取的 Secret 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;
}
}
步骤三:有了以上两个步骤,就可以写代码进行识别啦,话不多说,直接上代码
import java.net.URLEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import static com.lin.practice.voice_announcements.VoiceAnnouncements.read;
@Controllerpublic class ImgController {
//public static void main(String[] args) { // test(); // } @ResponseBody @RequestMapping(value = "/ocr", method = RequestMethod.POST)
public JSONObject test(@RequestPart(value = "file", required = false) MultipartFile file) {
ModelAndView mav = new ModelAndView("index");
//public static JSONObject test(){ // 请求url String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";//https://aip.baidubce.com/rest/2.0/ocr/v1/idcard,https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license String result = "";
JSONObject parseobject = null;
try {
// 本地文件路径 //String filePath = "C:\Users\mayn\Desktop\1596726642(1).png"; byte[] imgData = file.getBytes();
//byte[] imgData = FileUtil.readFileByBytes(filePath); String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param = "image=" + imgParam;
// String param = "image=" + imgParam+"&id_card_side=front"; // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 String accessToken = "24.25af24d873386e07025e113c44750dc1.2592000.1599316725.282335-21835341";
result = HttpUtil.post(url, accessToken, param);
parseObject = JSONArray.parseObject(result);
System.out.println(result);
read(result);
} catch (Exception e) {
e.printStackTrace();
}
return parseObject;
}
}
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;
}
}
import java.io.*;
/** * 文件读取工具类 */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();
}
}
}
}
/** * 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();
}
}
下面给出语音播报内容:pom中添加依赖,如果不成功,请下载后,用maven自行导入
命令如下: mvn install:install-file -Dfile=cloud.jar(本地包名) -DgroupId=com.hope.cloud -DartifactId=cloud -Dversion=1.0 -Dpackaging=jar
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.10</version>
</dependency>
另外需要下载jacob-1.17-M2-x86.dll,并添加到JDK的bin目录
下面上代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import com.jacob.com.Dispatch;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Variant;
/*将jacob-1.17-M2-x86.dll添加到JDK的bin目录和windows的system32目录(64位系统添加jacob-1.17-M2-x64.dll) * * * * */public class VoiceAnnouncements {
public static void main(String[] args) {
try {
StringBuilder stringbuilder = new StringBuilder();
//创建Scanner对象,接受从控制台输入 Scanner scanner = new Scanner(System.in);
String m = "-1";
//如果输入的是“t”,则结束服务 while (!"t".equalsIgnoreCase(stringbuilder.toString())) {
System.out.println("请输入需要语音播报的内容:");
read("请输入需要语音播报的内容");
while (true) {
String text = scanner.nextLine().trim();
if ("".equals(text)) {
break;
}
stringbuilder.append(text);
}
if (stringbuilder.toString().endsWith("t")) {
System.out.println("感谢使用");
read("感谢使用");
break;
} else {
System.err.println("需要播报的输入内容为:"+stringbuilder.toString());
//播报 read(stringbuilder.toString());
/** * 清空字符串 */ stringbuilder.delete(0, stringbuilder.length());
read("播报结束");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
/** * 根据字符串进行语音播报 * 问题:为什么方法为static * @param str */ public static void read(String str) {
ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
// 音量 0-100 sap.setProperty("Volume", new Variant(100));
// 语音朗读速度 -10 到 +10 sap.setProperty("Rate", new Variant(0));
// 获取执行对象 Dispatch sapo = sap.getObject();
// 执行朗读 Dispatch.call(sapo, "Speak", new Variant(str));
/*// 关闭执行对象 sapo.safeRelease(); // 关闭应用程序连接 sap.safeRelease();*/ }
}通过以上步骤,应该可以正确运行文字识别,并语音播报了,似不似很方便。
通过以上步骤,应该可以正确运行文字识别,并语音播报了,似不似很方便。