java调用百度接口识别图片中文字

package com.skynet.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;
import com.skynet.pojo.AddoilMark;
/**
 * @ClassName: IdentificationTicketUtil   
 * @Description: 百度识别图片中文字的类 
 * @author lizhenjie   
 * @date 2019年1月24日 上午10:57:38  
 * @version 1.0
 */
public class IdentificationTicketUtil {
    //设置APPID/AK/SK
    public static final String APP_ID = "11722411";
    public static final String API_KEY = "GBzpKtWlDTigpuRP1NQHLlmm";
    public static final String SECRET_KEY = "lWNw6sGGjomZUXtNNED7a6XdO3cztWmY";
    
    public static void main(String[] args) throws Exception{
      //  String url = "https://user-file.obs.cn-north-1.myhwclouds.com/shop-heatmap/20190122/d46f814716f8a052cf2f30092c5212b520190122172827.jpg";
      //  saveHeaderPic(url);
    }

    public static AddoilMark saveHeaderPic(String url) throws Exception {
        AddoilMark addoilMark = new AddoilMark();
            try {
                URL file = new URL(url);
                InputStream is = file.openStream();
                byte[] readInputStream = null;
                readInputStream = readInputStream(is);
                // 初始化一个AipOcr
                AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
                // 可选:设置网络连接参数
                client.setConnectionTimeoutInMillis(2000);
                client.setSocketTimeoutInMillis(60000);
                Map<String,Object> map = new HashMap<>();
                JSONObject res = client.basicGeneral(readInputStream, new HashMap<String, String>());
                String str = res.toString(2);
                int one = getCharacterPosition(str, "元", 1);
                int pat = getCharacterPosition(str, "中", 1);
                int two = getCharacterPosition(str, "元", 2);
                int three = getCharacterPosition(str, "元", 3);
                int four = getCharacterPosition(str, "元", 4);
                int L = getCharacterPosition(str, "L", 1);
                String stationName = str.substring(pat);
                stationName = stationName.substring(0, 7);
                addoilMark.setStationName(stationName);
                String orderId = str.substring(str.indexOf("订单号")+4, str.indexOf("车牌号"));
                orderId = orderId.substring(0,24);
                addoilMark.setOrderId(orderId);
                String carId = str.substring(str.indexOf("车牌号")+4);
                carId = carId.substring(0, 8);
                addoilMark.setCarId(carId);
                String oilName = str.substring(str.indexOf("油品种类")+5);
                oilName = oilName.substring(0,3);
                addoilMark.setOilName(oilName);
                String oilAmount = str.substring(str.indexOf("加油金额")+5,one);
                addoilMark.setOilAmount(oilAmount);
                String real = str.substring(str.indexOf("支付金额")+5, two);
                addoilMark.setRealAmount(real);
                String totalDiscount = str.substring(str.indexOf("优惠金额")+5,three);
                addoilMark.setTotalDiscount(totalDiscount);
                String totalAmount = str.substring(str.indexOf("实际加油金额")+7,four);
                addoilMark.setTotalAmount(totalAmount);
                String oilNum = str.substring(str.indexOf("实际加油升数")+7,L+1);
                addoilMark.setOilNum(oilNum); 
                String paymentTypes = str.substring(str.indexOf("付款方式")+5);
                paymentTypes = paymentTypes.substring(0, 4);
                addoilMark.setPaymentTypes(paymentTypes);
                String payee = str.substring(str.indexOf("收款方")+4);
                payee = payee.substring(0, 14);
                addoilMark.setPayee(payee);
            }catch(Exception e){
                e.printStackTrace();
            }
            return addoilMark;
             
    }

    /**
     * @Title: readInputStream  
     * @Description: 把字节流转换成字节数组  
     * @param @param is
     * @param @return
     * @param @throws IOException    设定文件   
     * @return byte[]    返回类型  
     * @throws
     */
    private static byte[] readInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=is.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        is.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * @Title: getCharacterPosition  
     * @Description: 获取字符在字符串中第n次出现的位置 
     * @param @param source
     * @param @param target
     * @param @param n
     * @param @return    设定文件   
     * @return int    返回类型  
     * @throws
     */
    public static int getCharacterPosition(String source, String target, int n) {
        // 这里是获取目标符号的位置
        Matcher slashMatcher = Pattern.compile(target).matcher(source);
        int mIdx = 0;
        while (slashMatcher.find()) {
            mIdx++;
            // 当目标符号第N次出现的位置
            if (mIdx == n) {
                break;
            }
        }
        return slashMatcher.start();
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用百度的OCR接口来实现Java调用百度接口图片文字的功能。首先,你需要注册百度开发者账号并创建应用,获取到API Key和Secret Key。 接下来,你可以使用Java的网络请求库,例如Apache HttpClient或OkHttp,来发送HTTP POST请求给百度OCR接口。在请求,你需要包含以下参数: - 接口地址:https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic - 请求参数:image(图片的Base64编码)、access_token(通过API Key和Secret Key获取的访问令牌) - 请求头:Content-Type设置为application/x-www-form-urlencoded 以下是一个示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class BaiduOCR { public static void main(String[] args) throws IOException { // 设置API Key和Secret Key String apiKey = "your_api_key"; String secretKey = "your_secret_key"; // 获取访问令牌 String accessToken = getAccessToken(apiKey, secretKey); // 图片路径 String imagePath = "path_to_your_image"; // 将图片转为Base64编码 String imageBase64 = getImageBase64(imagePath); // 调用百度OCR接口 String result = callBaiduOCR(imageBase64, accessToken); System.out.println(result); } // 获取访问令牌 private static String getAccessToken(String apiKey, String secretKey) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://aip.baidubce.com/oauth/2.0/token"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("grant_type", "client_credentials")); params.add(new BasicNameValuePair("client_id", apiKey)); params.add(new BasicNameValuePair("client_secret", secretKey)); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); httpClient.close(); return result.split("\"")[3]; } // 将图片转为Base64编码 private static String getImageBase64(String imagePath) { // TODO: 实现将图片转为Base64编码的逻辑 return ""; } // 调用百度OCR接口 private static String callBaiduOCR(String imageBase64, String accessToken) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("image", imageBase64)); params.add(new BasicNameValuePair("access_token", accessToken)); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); httpClient.close(); return result; } } ``` 请注意,在上述代码,你需要实现将图片转为Base64编码的逻辑,你可以使用第三方库,如Apache Commons Codec,来实现该功能。 希望这能帮到你!如果有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iamlzjoco

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值