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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值