• 百度API:通用文字识别(标准含位置版)c#


    百度API:通用文字识别(标准含位置版)c#

    demo地址:

    github:yateng817/baidu_ocr_demo_cs (github.com)

    gitee:sorrymakerTT/baidu_ocr_demo_cs (gitee.com)

    1.代码

    BaiduToken.cs

    用C#的方式获取token返回的数据是json数据,,需要的内容只有其中的access_token这一个内容,所以需要通过Newtonsoft将返回的json数据存储在BaiduToken对象中。

    //如果好用,请收藏地址,帮忙分享。
    public class BaiduToken
    {
    
        public string refresh_token { get; set; }
    
        public int expires_in { get; set; }
    
        public string session_key { get; set; }
    
        public string access_token { get; set; }
        
        public string scope { get; set; }
    
        public string session_secret { get; set; }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Program.cs

    • 将API Key 和 Secret Key分别填入clientId和clientSecret。(获取方式见:java调用通用文字识别

    • AccessToken类获取Token。

    • General类调用api。

    • getFileBase64(String filename),filename为图片路径。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Web;
    using System.Net.Http;
    using Newtonsoft.Json;
    
    namespace baidu_ocr_demo_cs
    {
        public static class AccessToken
    
        {
            // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
            // 返回token示例
            // public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";
    
            // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
            private static String clientId = "d8jNcYsMxNu4GeTTkWFlNouF";
            // 百度云中开通对应服务应用的 Secret Key
            private static String clientSecret = "SbyTO7NutbfhfWyON2VQa4C42fjWPz6P";
    
            public static String getAccessToken()
            {
                String authHost = "https://aip.baidubce.com/oauth/2.0/token";
                HttpClient client = new HttpClient();
                List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
                paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
                paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
    
                HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
                String result = response.Content.ReadAsStringAsync().Result;
    
                // Newtonsoft转换json数据
                String token = Newtonsoft.Json.JsonConvert.DeserializeObject<BaiduToken>(result).access_token;
                Console.WriteLine(token);
                return token;
            }
        }
        public class General
        {
            // OCR 通用识别
            public static string general()
            {
                string token = AccessToken.getAccessToken();
                string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + token;
                Encoding encoding = Encoding.Default;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                // 图片的base64编码
                string base64 = getFileBase64("img/test.png");
                String str = "image=" + HttpUtility.UrlEncode(base64);
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string result = reader.ReadToEnd();
                Console.WriteLine("OCR 通用识别:");
                Console.WriteLine(result);
                return result;
            }
    
            public static String getFileBase64(String fileName)
            {
                FileStream filestream = new FileStream(fileName, FileMode.Open);
                byte[] arr = new byte[filestream.Length];
                filestream.Read(arr, 0, (int)filestream.Length);
                string baser64 = Convert.ToBase64String(arr);
                filestream.Close();
                return baser64;
            }
        }
        internal class Program
        {
            static void Main(string[] args)
            {
                General.general();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
  • 相关阅读:
    SpringSecurity系列 - 09 SpringSecurity 自定义认证数据源实现用户认证
    MySQL使用ReplicationConnection导致的连接失效分析与解决
    Vue中的ref属性
    Win11任务栏太宽了怎么变窄?Win11任务栏宽度调整方法
    Electron安装问题
    【序列化二叉树】
    微信公众号获取openid流程
    VsCode 关于EsLint校验关闭严格模式
    python setup error: [WinError 2] 系统找不到指定的文件
    笔试强训Day(一)
  • 原文地址:https://blog.csdn.net/weixin_45800628/article/details/126248946