Java調用百度OCR文字識別的接口

調用百度OCR文字識別的接口,來自于百度官網,親測可以使用

  • 跳轉鏈接
  • FileUtil的下載鏈接
  • Base64Util下載鏈接
  • HttpUtil下載鏈接
  • GsonUtils下載鏈接
  • Accurate.java文件
package com.baidu.ai.aip;import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.HttpUtil;import java.net.URLEncoder;/**
* 通用文字識別(高精度含位置版)
*/
public class Accurate {/*** 重要提示代碼中所需工具類* 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 accurate() {// 請求urlString url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";try {// 本地文件路徑String filePath = "[本地文件路徑]";byte[] imgData = FileUtil.readFileByBytes(filePath);String imgStr = Base64Util.encode(imgData);String imgParam = URLEncoder.encode(imgStr, "UTF-8");String param = "image=" + imgParam;// 注意這里僅為了簡化編碼每一次請求都去獲取access_token,線上環境access_token有過期時間, 客戶端可自行緩存,過期后重新獲取。String accessToken = "[調用鑒權接口獲取的token]";String result = HttpUtil.post(url, accessToken, param);System.out.println(result);return result;} catch (Exception e) {e.printStackTrace();}return null;}public static void main(String[] args) {Accurate.accurate();}
}

所需要的4個文件具體內容

  • FileUtil
package com.example;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的Bufferbyte[] 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();}}}
}
  • Base64Util?
package com.example;/*** 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();}
}
  • HttpUtil?
package com.example;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;}
}
  • GsonUtils添加會報錯,刪除不影響最后的結果
  • 整體布局和結果如下圖所示

  • 拷貝輸出的結果,打開在線Json工具

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/447285.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/447285.shtml
英文地址,請注明出處:http://en.pswp.cn/news/447285.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

做好7步 迅速成為行業專家

行行出狀元&#xff0c;但不一定人人能成為行業專家或權威。無論是做獨立顧問&#xff0c;還是手下有250名員工的工廠主管&#xff0c;都是在用自己多年豐富經驗在幫助企業成功。既然有了專業知識和經驗&#xff0c;為什么不把它最大化利用&#xff0c;來建立自己的行業權威&am…

redis常用命令與特性

keys * 返回滿足條件的所有key&#xff0c;可以模糊匹配select 數字0-15&#xff0c;進行數據庫切換&#xff0c;默認0-15個exists 是否存在指定的keypersist 取消過期時間 select 選擇數據庫 &#xff08;0-15&#xff0c;總共16個數據庫&#xff09;move key index 將當前數據…

緊急不代表重要:管理時間的六個秘密

當整個世界都永遠在跟集中精神做事做對的時候&#xff0c;怎么辦&#xff1f;Managershare&#xff1a;“世界上效率最高的程序員有什么相同之處&#xff1f;不是經驗&#xff0c;薪水或者花在一個項目上的時間&#xff0c;而是他們的老板創造了一個免于走神的環境。”這老板太…

redis安全

定期打補丁禁止一些高危命令 &#xff08;flushdb、keys *、flushall&#xff09;以低權限運行 Redis 服務禁止外網訪問 Redis設置訪問密碼 足夠復雜&#xff0c;防止暴力破解 requirepass xxxxxxxx訪問權限 內網通過acl限制可以訪問redis的ip和端口

如何在三個月內獲得三年的工作經驗

在多年的工作生涯中&#xff0c;總會目睹一批人的升職像火箭速度一樣。 而總有一批人&#xff0c;就像蝸牛一樣&#xff0c;工作崗位和職位幾乎從來不變。 我們看看&#xff0c;2個名人的快速成長史。 一個是教英語的李陽&#xff0c;他讀大學時成績不好&#xff0c;英語不…

Redis Cluster集群模式

Redis Cluster 它是Redis的分布式解決方案&#xff0c;在Redis 3.0版本正式推出的&#xff0c;有效解決了Redis分布式方面的需求。當遇到單機內存、并發、流量等瓶頸時&#xff0c;可以采用Cluster架構達到負載均衡的目的。數據分布理論: 分布式數據庫首要解決把整個數據集按照…

永遠和靠譜的人在一起!

巴菲特每年都會同大學生進行座談&#xff0c;在一次交流會上&#xff0c;有學生問他&#xff1a;您認為一個人最重要的品質是什么?巴菲特沒有正面回答這個問題&#xff0c;而是講了一個小游戲&#xff0c;名為&#xff1a;買進你同學的10%。 巴菲特說&#xff1a;現在給你們一…

Redis事務詳解

傳統事務的特性 原子性一致性隔離性&#xff1a;事務之間互不干擾持久化&#xff1a;一旦事務提交&#xff0c;無法修改 Redis事務機制 MULTI、EXEC、DISCARD和WATCH命令是Redis事務功能的基礎。Redis事務允許在一次單獨的步驟中執行一組命令&#xff0c;并且可以保證如下兩個…

工作的最終目的

當時公司招了大批應屆本科和研究生畢業的新新人類。平均年齡25歲。那個新的助理&#xff0c;是經過多次面試后&#xff0c;我親自招回來的一個女孩。名牌大學本科畢業&#xff0c;聰明&#xff0c;性格活潑。私下里我得承認&#xff0c;我招她的一個很重要的原因&#xff0c;除…

銷售員所做的一切工作最終目的就是為了成交

&#xff08;1&#xff09;最后一次報價禁忌.報價過晚或者過于匆忙步幅度太大&#xff0c;顯得過于慷慨;讓步幅度太小&#xff0c;顯得毫無意義當談判進展到最后&#xff0c;雙方只是在最后的某一兩個問題上尚有不同意見&#xff0c;過讓步才能求得一致&#xff0c;簽訂協議。在…

Redis java客戶端操作

jedis jedis官方指定的redis java客戶端&#xff0c;將其導入到pom.xml問價內 <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><vers…

HEVC/H265 namespace 介紹

在 HEVC/H265 代碼中&#xff0c;有三個使用的namespace&#xff1a; 1. df 2. df::program_options_lite 3. RasterAddress 對于第一個 df 的namespace&#xff0c;我一直百思不得其解&#xff0c;df 是什么含義&#xff1f;老外對起名是很重視的&#xff0c;肯定有原因。…

Redis整合Springboot實現數據共享

代碼的整體結構 RedisSessionConfig.java package com.cc.springbootredissession.config;import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;Configuration E…

人生什么最重要

什么最重要 20歲的人說,學習成績最重要.一次考試分數,可以把人分為三六九等.&#xff02;博士&#xff02;,&#xff02;本科&#xff02;,&#xff02;大專&#xff02;&#xff02;高職&#xff02;&#xff02;中專&#xff02;,成績好的上好學校,成績差的上差學校;成績好的…

Redis整合Springboot實現單機配置

整體結構 配置文件 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/…

撐起整個互聯網的7大開源技術

撐起整個互聯網的7大開源技術 很多人可能尚未意識到&#xff0c;我們使用的電腦中運行有開源軟件&#xff0c;手機中運行有開源軟件&#xff0c;家里的電視也運行有開源軟件&#xff0c;甚至小小的數碼產品中也運行有開源軟件&#xff0c;尤其是互聯網服務器端軟件&#xff0c…

Redis整合springboot實現哨兵模式

整體結構 RedisConfig package com.cc.springredis.config;import com.cc.springredis.RedisUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.R…

Redis整合springboot實現集群模式

整體結構 Redis.config package com.cc.springredis.config;import com.cc.springredis.RedisUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection…

一個窮人是從什么時候開始有錢的?

2010年&#xff0c;文野31歲那年&#xff0c;買房后第二年&#xff0c;完成了「人生中最重要的一次轉變」。 這一年&#xff0c;他在心里對自己的定位&#xff0c;從窮人變成了有錢人。 「一些人哪怕有錢了&#xff0c;心里也永遠甩不脫窮的影子。」這是我曾經在《 階段性勝…

Redis整合springboot實現消息隊列

publisher消息的發出 代碼整體的結構 publisherConfig package com.cc.springbootredispublisher.config;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.conne…