腾讯AI开放平台-名片OCR接口--C#代码

东搬搬西搬搬凑齐了记录下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;

namespace YM
{
    public class txApics
    {
        public string app_id = "appId";
        public string app_key = "appKey";
        public string GetOCR()
        {
            string rtn = string.Empty;
            byte[] image = System.IO.File.ReadAllBytes("本地图片地址");
            string imgBase = Convert.ToBase64String(image);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("app_id", app_id);
            dic.Add("time_stamp", GenerateTimeStamp());
            dic.Add("nonce_str", GetNonceStr());
            dic.Add("sign", "");
            dic.Add("image", imgBase);
            rtn = urlencode(dic);
            rtn += "&app_key=" + app_key;
            rtn = MD5Encrypt(rtn, new UTF8Encoding()).ToUpper();
            dic["sign"] = rtn;
            dic = dic.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            HttpWebResponse response = CreatePostHttpResponse1("https://api.ai.qq.com/fcgi-bin/ocr/ocr_bcocr", dic, null);
            using (Stream s = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                rtn = reader.ReadToEnd();
            }
            return rtn;
        }
        private HttpWebResponse CreatePostHttpResponse1(string url, IDictionary<string, string> parameters, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, encode(parameters[key]));
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, encode(parameters[key]));
                        i++;
                    }
                }
                //必须使用utf8
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }
        public string urlencode(Dictionary<string, string> dic)
        {
            string rtn = string.Empty;
            dic = dic.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            foreach (var item in dic)
            {
                if (string.IsNullOrEmpty(item.Value))
                {
                    continue;
                }
                rtn += item.Key + "=" + encode(item.Value) + "&";
            }
            return rtn.TrimEnd('&');
        }
        public string encode(string str)
        {
            string rtn = string.Empty;
            foreach (char item in str)
            {
                if (Microsoft.JScript.GlobalObject.encodeURIComponent(item.ToString()).Length > 1)
                {
                    rtn += Microsoft.JScript.GlobalObject.encodeURIComponent(item.ToString()).ToUpper();
                }
                else
                {
                    rtn += item;
                }
            }
            return rtn;
        }
        public string MD5Encrypt(string input, Encoding encode)
        {
            if (string.IsNullOrEmpty(input))
            {
                return null;
            }
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(encode.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        public string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        public string GetNonceStr()
        {
            return Guid.NewGuid().ToString("N");
        }
    }
}


引入 Microsoft.JScript

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值