百度云-图片识别接口调用Demo

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace RC.Software.OCR
{
    public class BaiduHelper
    {
        private static readonly string clientId = "6s4GlTNTaTcVip5SgK******"; //"百度云应用的AK";
        private static readonly string clientSecret = "VtAAT8YqxVb7TrOuVXBhSZnPat*******"; //"百度云应用的SK";

        /// 
        /// 图片识别
        /// 
        /// 
        /// 
        public static string Ocr(string filePath)
        {
            try
            {
                var img = HttpUtility.UrlEncode(GetBase64FromImage(filePath));
                var token = GetAccessToken();
                token = new Regex(
                    "\"access_token\":\"(?[^\"]*?)\"",
                    RegexOptions.CultureInvariant
                    | RegexOptions.Compiled
                ).Match(token).Groups["token"].Value.Trim();

                //var url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
                var url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
                var list = new List>
                {
                    new KeyValuePair("access_token", token),
                    new KeyValuePair("image", img),
                    new KeyValuePair("language_type", "CHN_ENG")
                };
                var data = new List();
                foreach (var pair in list)
                    data.Add(pair.Key + "=" + pair.Value);
                var json = HttpPost(url, string.Join("&", data.ToArray()));
                return json;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public static string GetBase64FromImage(string imagefile)
        {
            string base64String;
            try
            {
                byte[] arr;
                using (var bmp = new Bitmap(imagefile))
                {
                    using (var ms = new MemoryStream())
                    {
                        bmp.Save(ms, ImageFormat.Jpeg);
                        arr = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(arr, 0, (int)ms.Length);
                        ms.Close();
                    }
                }
                base64String = Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                throw new Exception("Something wrong during convert!");
            }
            return base64String;
        }

        public static string GetAccessToken()
        {
            var url = "https://aip.baidubce.com/oauth/2.0/token";
            var list = new List>
            {
                new KeyValuePair("grant_type", "client_credentials"),
                new KeyValuePair("client_id", clientId),
                new KeyValuePair("client_secret", clientSecret)
            };
            var data = new List();
            foreach (var pair in list)
                data.Add(pair.Key + "=" + pair.Value);
            return HttpGet(url, string.Join("&", data.ToArray()));
        }

        public static string HttpGet(string url, string data)
        {
            var request = (HttpWebRequest)WebRequest.Create(url + (data == "" ? "" : "?") + data);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var stream = response.GetResponseStream();
                string s = null;
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
                    {
                        s = reader.ReadToEnd();
                        reader.Close();
                    }
                    stream.Close();
                }
                return s;
            }
        }

        public static string HttpPost(string url, string data)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(data);
            var stream = request.GetRequestStream();
            var writer = new StreamWriter(stream, Encoding.GetEncoding("gb2312"));
            writer.Write(data);
            writer.Close();

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var res = response.GetResponseStream();
                if (res != null)
                {
                    var reader = new StreamReader(res, Encoding.GetEncoding("utf-8"));
                    var retString = reader.ReadToEnd();
                    reader.Close();
                    res.Close();
                    return retString;
                }
            }
            return "";
        }
    }
}

你可能感兴趣的:(C#)