SpringBoot项目(百度AI整合)——如何在Springboot中使用文字识别OCR入门

news2024/10/7 3:28:42

在这里插入图片描述

前言

前言:本系列博客尝试结合官网案例,阐述百度 AI 开放平台里的组件使用方式,核心是如何在spring项目中快速上手应用。

本文介绍如何在Springboot中使用百度AI的文字识别OCR

在这里插入图片描述

其他相关的使用百度AI的文章列表如下:

如何在Springboot中使用语音文件识别 & ffmpeg的安装和使用

在这里插入图片描述

文章目录

  • 前言
  • 引出
  • 小经验:如何使用官方文档
    • 1.API文档的使用
    • 2.HTTP-SDK文档的使用
  • 基于官网案例demo的实现
    • 1.使用AipOcr客户端
    • 2.使用官网的HttpUtil工具类
  • 附录:官网的工具类
    • 1.Base64Util图片编码工具
    • 2.FileUtil读取文件工具类
    • 3.基于Google的gson的Json工具类
    • 4.Http请求发起和获得响应工具类
  • 总结

引出


1.从官网demo到idea中使用;
2.如何阅读官网的说明文档,小经验分享;

在这里插入图片描述

小经验:如何使用官方文档

https://ai.baidu.com/ai-doc/index/OCR

https://ai.baidu.com/ai-doc/OCR/Ek3h7xypm

在这里插入图片描述

1.API文档的使用

万里长征第一步,Ctrl c + v,复制粘贴

在这里插入图片描述

2.HTTP-SDK文档的使用

网络请求SDK案例

在这里插入图片描述

基于官网案例demo的实现

从官网的案例到spring项目整合

在这里插入图片描述

1.使用AipOcr客户端

BaiduOcrPro实体类

package com.tianju.config.baidu;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * OCR相关的配置
 */

@Component
@ConfigurationProperties(prefix = "baidu.ocr")
@PropertySource("classpath:config/baiduAip.properties")

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaiduOcrPro {
    private String appId;
    private String apiKey;
    private String secretKey;
}

初始化AipOcr,放到spring容器中

package com.tianju.config.baidu;

import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.speech.AipSpeech;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 百度相关的配置文件
 */
@Configuration
public class BaiduConfig {

    @Autowired
    private BaiduOcrPro baiduOcrPro;

    /**
     * 图像相关的 AipOcr
     * @return AipOcr 放容器中
     */
    @Bean
    public AipOcr aipOcr(){
        AipOcr aipOcr = new AipOcr(baiduOcrPro.getAppId(),
                baiduOcrPro.getApiKey(),
                baiduOcrPro.getSecretKey());
        // 可选:设置网络连接参数
        aipOcr.setConnectionTimeoutInMillis(2000);
        aipOcr.setSocketTimeoutInMillis(60000);
        return aipOcr;
    }

}

controller层进行调用

package com.tianju.config.controller;

import com.baidu.aip.ocr.AipOcr;
import com.tianju.config.resp.HttpResp;
import com.tianju.config.util.baidu.Base64Util;
import com.tianju.config.util.baidu.FileUtil;
import com.tianju.config.util.baidu.HttpUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.HashMap;


@RestController
@RequestMapping("/api/baidu/ocr")
public class BaiduOCRController {

    @Autowired
    private AipOcr aipOcr;

    // http://124.70.138.34:9000/hello/1.jpg
    @GetMapping("/imgUrl")
    public HttpResp ocrFromImgUrl(String imgUrl){

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        /**
         * 网络图像
         */
        JSONObject res = aipOcr.basicGeneralUrl(
                imgUrl,
                options
        );

        /**
         * {"words_result":
         * [{"probability":{"average":0.9994496107,"min":0.9990026355,"variance":1.469044975E-7},
         *  "words":"爱我中华"}],
         * "log_id":1705920508293856573,"words_result_num":1,"language":3,"direction":0}
         */

        JSONArray wordsResult = (org.json.JSONArray)res.get("words_result");
        JSONObject o = (JSONObject) wordsResult.get(0);
        Object words = o.get("words");
        System.out.println(words);

        System.out.println("######################");
        System.out.println(res.toString(2));
        return HttpResp.success(words);
    }

}

在这里插入图片描述

2.使用官网的HttpUtil工具类

package com.tianju.config.controller;

import com.baidu.aip.ocr.AipOcr;
import com.tianju.config.resp.HttpResp;
import com.tianju.config.util.baidu.Base64Util;
import com.tianju.config.util.baidu.FileUtil;
import com.tianju.config.util.baidu.HttpUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.HashMap;


@RestController
@RequestMapping("/api/baidu/ocr")
public class BaiduOCRController {

    /**
     * 以下为官网的案例,token的方式
     * https://ai.baidu.com/ai-doc/OCR/zk3h7xz52
     */
    public static String generalBasic() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            // 本地文件路径
            String filePath = "D:\\Myprogram\\springboot-workspace\\spring-project\\baidu-api\\src\\main\\resources\\static\\ocr_test.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;
            System.out.println(param);

            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = "24.2f4d3e23a805ba89627472c38addcdcd.2592000.1698147302.282335-38781099";

            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) {
        generalBasic();
    }
}

在这里插入图片描述

附录:官网的工具类

1.Base64Util图片编码工具

package com.tianju.config.util.baidu;

/**
 * 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();
    }
}

2.FileUtil读取文件工具类

package com.tianju.config.util.baidu;

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();
            }
        }
    }
}

3.基于Google的gson的Json工具类

/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.tianju.config.util.baidu;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * Json工具类.
 */
public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }
}

4.Http请求发起和获得响应工具类

package com.tianju.config.util.baidu;

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;
    }
}

总结

1.从官网demo到idea中使用;
2.如何阅读官网的说明文档,小经验分享;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1038496.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【SpringBoot】-SpringBoot配置文件

作者&#xff1a;学Java的冬瓜 博客主页&#xff1a;☀冬瓜的主页&#x1f319; 专栏&#xff1a;【Framework】 主要内容&#xff1a;.properties 配置文件和 .yml 配置文件中 配置信息的设置和获取。关于IDEA乱码的解决。.yml 配置文件的 方式语法分析和演示。 .yml配置文件 …

芯片验证就是一次旅行

如果你国庆希望去一个你不曾去过的城市旅行&#xff0c;比如“中国苏州”。对游客来说&#xff0c;它是个蛮大的城市&#xff0c;有许多景点可以游玩&#xff0c;还有许多事情可以做。但实际上&#xff0c;即使最豪也最清闲的游客也很难看苏州的所有方方面面。同样的道理也适用…

第 4 章 串(文本行编辑实现)

1. 背景说明 该文本编辑器利用串的堆实现&#xff0c;其中对串的原始存储方式基本不作修改&#xff08;有部分修改之处&#xff09;&#xff0c;优化之处在于在串的末尾加上了一个空字符&#xff0c;目的是区分字符串结尾&#xff0c;便于将串保存在文件中&#xff0c;且该优化…

JavaScript入门——(2)基础语法(上)

一、JavaScript介绍 1.1 JavaScript是什么 1.1.1 JavaScript是什么&#xff1f; JavaScript是一种运行在客户端&#xff08;浏览器&#xff09;的编程语言&#xff0c;实现人机交互效果。 注意&#xff1a;HTML和CSS是标记语言。 1.1.2 作用&#xff08;做什么&#xff1f…

8月最新修正版风车IM即时聊天通讯源码+搭建教程

8月最新修正版风车IM即时聊天通讯源码搭建教程。风车 IM没啥好说的很多人在找,IM的天花板了,知道的在找的都知道它的价值,开版好像就要29999,后端加密已解,可自己再加密,可反编译出后端项目源码,已增加启动后端需要google auth双重验证,pc端 web端 wap端 android端 ios端 都有 …

小米机型解锁bl 跳“168小时”限制 操作步骤分析

写到前面的安全提示 了解解锁bl后的风险&#xff1a; 解锁设备后将允许修改系统重要组件&#xff0c;并有可能在一定程度上导致设备受损&#xff1b;解锁后设备安全性将失去保证&#xff0c;易受恶意软件攻击&#xff0c;从而导致个人隐私数据泄露&#xff1b;解锁后部分对系…

老胡的周刊(第109期)

老胡的信息周刊[1]&#xff0c;记录这周我看到的有价值的信息&#xff0c;主要针对计算机领域&#xff0c;内容主题极大程度被我个人喜好主导。这个项目核心目的在于记录让自己有印象的信息做一个留存以及共享。 &#x1f3af; 项目 lobe-chat[2] LobeChat 是一个开源的、可扩展…

面试题:说说Java并发运行中的一些安全问题

文章目录 1.什么是多线程并发运行安全问题&#xff1f;2.用synchronized修饰的方法3.同步块4.使用Synchronized修饰静态方法5.互斥锁6.死锁现象7.wait()和sleep()的区别 1.什么是多线程并发运行安全问题&#xff1f; 当多个线程并发操作一个数据时&#xff0c;由于线程操作的时…

在Linux上安装Percona Toolkit工具

安装步骤 1. 下载安装包 下载地址&#xff1a;https://www.percona.com/software/database-tools/percona-toolkit 2.上传并解压 上传tar包到服务器&#xff0c;并通过tar -zxvf 文件名.tar.gz解压。工具在bin文件夹中&#xff0c;这个是免安装的。 3. 配置环境变量 配置…

安装OpenSearch

title: “安装opensearch” createTime: 2021-11-30T19:13:4508:00 updateTime: 2021-11-30T19:13:4508:00 draft: false author: “name” tags: [“es”,“安装”] categories: [“OpenSearch”] description: “测试的” 说明 基于Elasticsearch7.10.2 的 opensearch-1.1.…

gRPC之实现TLS通信加密_已设置图床

gRPC之实现TLS通信加密 "crypto/tls"包 “crypto/tls” 是 Go 编程语言中的一个包&#xff0c;用于实现 TLS&#xff08;传输层安全&#xff09;协议。TLS 协议用于加密和保护网络通信&#xff0c;通常用于保护敏感数据的传输&#xff0c;如密码、支付信息等。在 G…

详解--计算机存储相关(寄存器、CPU Cache、内存、外存)

CPU寄存器、高速缓冲存储器、主存储器、外存储器 1. 主存储器 参考链接–主存 参考链接–内存 主存储器简称 主存&#xff0c;又称 内存储器&#xff08;简称 内存&#xff09;。作用 暂时存放CPU中的运算数据。存放指令和数据&#xff0c;并能由中央处理器&#xff08;CPU&a…

什么是Service Worker?它在PWA中的作用是什么?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ Service Worker的作用是什么&#xff1f;⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前…

1066 二级C语言-自定义函数

输入一个正数x和一个正整数n&#xff0c;求下列算式的值。要求定义两个调用函数&#xff1a; &#xff08;1&#xff09;fact(n)计算n的阶乘&#xff1b; &#xff08;2&#xff09;mypow(x,n)计算x的n次幂&#xff08;即xn&#xff09;&#xff0c;两个函数的返回值类型是do…

HEC-HMS和HEC-RAS水文模型、防洪评价报告编制及洪水建模、洪水危险性评价等相关案例解析

► HEC-RAS一维、二维建模方法及应用 【目标】&#xff1a; 1.掌握一维数学模型基本地形导入方法 2.掌握恒定流、非恒定流一维数学模型水流计算方法 3.掌握一维数学模型计算结果分析&#xff0c;水面线成果分析及调试&#xff1b;流速分布图输出方法 4.掌握一维数学模型增设构…

如何让一个uniform variable在多级shader中都起作用(类似C语言的全局变量)?

GLSL编程中通常设计多个shader&#xff0c;如vertex shader, fragment shader等等。在最近的某个项目中&#xff0c;我需要定义一个变量&#xff0c;该变量类似C语言中的全局变量&#xff0c;要同时在两个shader中都起作用。c - OpenGL Uniform Across Multiple Shaders - Stac…

2023-9-23 区间选点

题目链接&#xff1a;区间选点 #include <iostream> #include <algorithm>using namespace std;const int N 100010;int n;struct Range {int l, r;bool operator< (const Range &W) const{return r < W.r;} }range[N];int main() {scanf("%d"…

MyBatisPlus + ShardingJDBC 批量插入不返回主键ID

本文讲述一个由 ShardingJDBC 使用不当引起的悲惨故事。 一. 问题重现 有一天运营反馈我们部分订单状态和第三方订单状态无法同步。 根据现象找到了不能同步订单状态是因为 order 表的 thirdOrderId 为空导致的&#xff0c;但是这个字段为啥为空&#xff0c;排查过程比较波折…

NebulaGraph实战:2-NebulaGraph手工和Python操作

图数据库是专门存储庞大的图形网络并从中检索信息的数据库。它可以将图中的数据高效存储为点&#xff08;Vertex&#xff09;和边&#xff08;Edge&#xff09;&#xff0c;还可以将属性&#xff08;Property&#xff09;附加到点和边上。本文以示例数据集basketballplayer为例…

java的Map和Set集合

Set集合 一.HashSet HashSet 元素是无序的 向Hashset中添加元素时&#xff0c;是如何判断元素是否重复的: 添加元素时&#xff0c;如果用equals判断效率太低&#xff0c;因为equals是一个一个字符比较 HashSet底层用到hashCode和equals 一个内容&#xff1a;"sahdihwo&q…