Java 百度API识别图片文字,根据图片提取文字
图片(例)
提取之后的字
代码附上
ImgToWords.java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mddb.util.photoscan.util.Base64Util;
import com.mddb.util.photoscan.util.HttpUtil;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @description: 百度云提取图片上的文字
* @author: LCHYUE
* @time: 2021/6/24 15:28
*/
public class ImgToWords {
/**
* 根据图片获取图片中信息
*
* @param file
* @return
*/
public static String convertPicToStr(MultipartFile[] file) {
String strTwo = "";
//百度图片验证接口
String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
try {
String apiKey = "xxxxxxxxxxxxxxx";//使用自己申请的apiKey
String secretKey = "xxxxxxxxxxxxx";//使用自己申请的secretKey
String tocken = "";
//请求百度tocken接口,获取tocken信息,存到数据库中
String tockens = getAuth(apiKey, secretKey);
tocken = tockens;
//去请求加载百度
for (int i = 0; i < file.length; i++) {
byte[] imgData = file[i].getBytes();
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param = "image=" + imgParam;
// 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
//String accessToken = "24.f75c3ee94c663b3ac2097f16ae1099cd.2592000.1622122152.282335-24066719";
String str = HttpUtil.post(url, tocken, param);
JSONObject parse = JSONObject.parseObject(str);
JSONArray jsonArray = parse.getJSONArray("words_result");
for (int j = 0; j < jsonArray.size(); j++) {
JSONObject parses = JSONObject.parseObject(jsonArray.get(j).toString());
strTwo += parses.get("words").toString();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return strTwo;
}
/**
* 获取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(Boolean.parseBoolean(result));
JSONObject jsonObject = JSONObject.parseObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
}
/**
* @Description: 根据路径装化成 MultipartFile
* @Param: imgUrlList 文件路径
* @return: MultipartFile
* @Author: LCHYUE
* @Date: 2021/6/24
*/
public static MultipartFile[] fileToMultipartFile(List<String> imgUrlList) {
FileInputStream fileInputStream = null;
int fileSize = imgUrlList.size();//图片的页数
MultipartFile[] multipartFiles = new MultipartFile[fileSize];
try {
for (int i = 0; i < fileSize; i++) {
String fileUrl = imgUrlList.get(i);
//linux---start---
// String result = fileUrl.replaceAll("\\\\", File.separator);
// File file = new java.io.File(result);
//linux--end----
//windows--start
File file = new java.io.File(fileUrl);
//windows--end
fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
multipartFiles[i] = multipartFile;
}
return multipartFiles;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
List<String> imgUrlList = new ArrayList<>();
imgUrlList.add("D:\\Desktop\\书\\诗.png");
MultipartFile[] multipartFiles = fileToMultipartFile(imgUrlList);
String strTwo = convertPicToStr(multipartFiles);
System.out.println(strTwo);
}
}