使用腾讯智能文字识别 OCR 对图片进行文字识别java
前段时间有个项目须要一个图片识别转换成文字的功能,后来考虑了一下选择了腾讯云的文字识别OCR。当时对接的过程当中以为有一些地方确实有些坑,因此再记录一下, 避免之后忘记。也但愿能给须要的朋友提供一些帮助。git
能够参考一下腾讯云官网的连接:文字识别OCRgithub
我是直接经过QQ帐号进行注册登陆,你们也能够查看腾讯云官方教程进行注册,注册腾讯云api
建立新秘钥,可能会弹出窗口提示你不安全,建立子用户之类,这个看你我的须要,想要建立子用户就能够建立,不想建立的话直接点解继续使用便可。最后在左侧菜单栏选择云API秘钥->API秘钥管理,点击 新建秘钥 便可,记录下对应的APPID、SecretId、SecretKey,在项目中须要的地方替换掉。 缓存
在腾讯云菜单中选择万象优图(连接),点击 Bucket管理,以后点击页面上的 绑定Bucket安全
会提示 该服务须要建立角色微信
点击 受权 网络
以后继续选择 赞成受权app
以后会提示进行身份验证,使用微信扫描便可,也能够选择使用备选验证方式等ide
再次点击页面上的 绑定Bucket
新增方式选择 新建
所属项目不用改,直接用 默认项目
名称本身命名便可,只要符合规则,其他没什么限制,记住这个名称,以后在项目中会须要用到
其他选项能够不须要改动
记住建立以后的bucket名称,以后在项目中须要的地方替换掉
若是上面的说明有比较模糊的地方,也能够参考腾讯云官网的操做指引。
具体说明能够参考腾讯云官网的说明:鉴权签名,我这里使用的java语言,因此直接使用的java签名示例。 将官网给出的代码拷贝到java文件中便可,以后须要使用签名的时候直接调用文件中的appSign方法
这一步是当时我以为比较麻烦的,由于这个接口拼起来有点费劲。而且当前效果是识别本地文件
官方给出的文档在这儿:OCR-通用印刷体识别,若是出现了一些错误也能够在这里找对应的状态码查看缘由。
/** * 配置Connection对象 * @throws Exception */
private static HttpURLConnection handlerConnection(String path, String imageName) throws Exception {
URL url = new URL(URL);
// 获取HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); // 设置 Post 请求方式
connection.setDoOutput(true); // 容许输出流
connection.setDoInput(true); // 容许输入流
connection.setUseCaches(false); // 禁用缓存
// 设置请求头
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
connection.setRequestProperty("authorization", sign());
connection.setRequestProperty("host", HOST);
System.out.println( "请求头设置完成");
// 获取HttpURLConnection的输出流
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
StringBuffer strBufparam = new StringBuffer();
strBufparam.append(LINE_END);
// 封装键值对数据参数
String inputPartHeader1 = "--" + BOUNDARY + LINE_END + "Content-Disposition:form-data;name=\""+ "appid" +"\";" + LINE_END + LINE_END + APPID + LINE_END;
String inputPartHeader2 = "--" + BOUNDARY + LINE_END + "Content-Disposition:form-data;name=\""+ "bucket" +"\";" + LINE_END + LINE_END + BUCKET + LINE_END;
strBufparam.append(inputPartHeader1);
strBufparam.append(inputPartHeader2);
// 拼接完成后,一块儿写入
outputStream.write(strBufparam.toString().getBytes());
// 写入图片文件
String imagePartHeader = "--" + BOUNDARY + LINE_END +
"Content-Disposition: form-data; name=\"" + "image" + "\"; filename=\"" + imageName + "\"" + LINE_END +
"Content-Type: image/jpeg" + LINE_END + LINE_END;
byte[] bytes = imagePartHeader.getBytes();
outputStream.write(bytes);
// 获取图片的文件流
String imagePath = path + File.separator + imageName;
InputStream fileInputStream = getImgIns(imagePath);
byte[] buffer = new byte[1024*2];
int length = -1;
while ((length = fileInputStream.read(buffer)) != -1){
outputStream.write(buffer,0,length);
}
outputStream.flush();
fileInputStream.close();
// 写入标记结束位
byte[] endData = ("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + LINE_END + BOUNDARY + "--" + LINE_END).getBytes();//写结束标记位
outputStream.write(endData);
outputStream.flush();
return connection;
}
复制代码
/** * 根据文件名获取文件输入流 * @throws FileNotFoundException */
private static InputStream getImgIns(String imagePath) throws FileNotFoundException {
File file = new File(imagePath);
FileInputStream is = new FileInputStream(file);
return is;
}
/** * 把输入流的内容转化成字符串 * @param is * @return * @throws IOException */
public static String readInputStream(InputStream is) throws IOException{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int length=0;
byte[] buffer=new byte[1024];
while((length=is.read(buffer))!=-1){
baos.write(buffer, 0, length);
}
is.close();
baos.close();
return baos.toString();
}
/** * 签名方法,调用Sign文件中的appSign方法生成签名 * @return 生成后的签名 */
public static String sign(){
long expired = 10000;
try {
return Sign.appSign(APPID, SECRET_ID, SECRET_KEY, BUCKET, expired);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
复制代码
/*** * 上传图片进行识别 * @param urlStr 请求地址 * @param path 图片所在文件夹的路径 * @param imageName 图片名称 */
public void uploadImage(String path, String imageName) {
new Thread(){
@Override
public void run() {
try {
// 配置HttpURLConnection对象
HttpURLConnection connection = handlerConnection(path, imageName);
// 链接HttpURLConnection
connection.connect();
// 获得响应
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
String result = readInputStream(connection.getInputStream());//将流转换为字符串。
System.out.println("请求成功:" + result);
} else {
String errorMsg = readInputStream(connection.getErrorStream());//将流转换为字符串。
System.out.println("请求失败:" + errorMsg);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println( "网络请求出现异常: " + e.getMessage());
}
}
}.start();
}
复制代码
源码地址:TencentOCRDemo(欢迎 Star,谢谢!)
使用Git下载:git clone https://github.com/beichensky/TencentOCRDemo.git
关于使用 Java 语言抵用腾讯云文字OCR识别的方式,大概就在这里了,若是有说的很差或者不清楚地地方,欢迎你们指正。