人脸识别 API C# 示例代码

阿里的人脸识别 API,有多种语言的示例代码,但没有 c# 的。

https://help.aliyun.com/document_detail/67818.html?spm=a2c4g.11186623.6.556.rD16LC 

于是今天有了:

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

namespace AliFace
{
    class Program
    {
        /// <summary>
        /// 计算MD5+BASE64
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String MD5Base64(String s)
        {
            if (s == null)
                return null;

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(s));

            return Convert.ToBase64String(result);
        }
        
        /// <summary>
        /// 计算 HMAC-SHA1
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static String HMACSha1(String data, String key)
        {
            String result;
            try
            {
                HMACSHA1 hmac = new HMACSHA1()
                {
                    Key = Encoding.Default.GetBytes(key)
                };

                byte[] rawHmac = hmac.ComputeHash(Encoding.Default.GetBytes(data));
                result = Convert.ToBase64String(rawHmac);
            }
            catch (Exception e)
            {
                throw new Exception("Failed to generate HMAC : " + e.Message);
            }
            return result;
        }
        
        /// <summary>
        /// GMT 时间格式
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static String toGMTString(DateTime date)
        {
            return date.ToString("r");
        }

        /// <summary>
        /// 阿里人像比对接口地址
        /// </summary>
        public static string VerifyURL = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";

        /// <summary>
        /// 发送 Post 请求
        /// </summary>
        /// <param name="body"></param>
        /// <param name="ak_id"></param>
        /// <param name="ak_secret"></param>
        /// <returns></returns>
        public static String SendVerifyPost(String body, String ak_id, String ak_secret)
        {
            // https 访问需要设置  ************************************************ 需要的
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

            String method = "POST";
            String accept = "application/json";
            String content_type = "application/json";
            String path = "/face/verify";
            String date = toGMTString(DateTime.Now);
            // 1.对body做MD5+BASE64加密
            String bodyMd5 = MD5Base64(body);
            String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
                    + path;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            String authHeader = "Dataplus " + ak_id + ":" + signature;

            byte[] postData = Encoding.Default.GetBytes(body);


            string result = "";
            HttpWebRequest req = WebRequest.Create(VerifyURL) as HttpWebRequest;
            HttpWebResponse res = null;
            if (req != null)
            {
                req.Method = method;
                req.Accept = accept;
                req.ContentType = content_type;

                // Date 参数不可直接设置,使用Header.Add 会报错    ************************************************ 需要的
                MethodInfo priMethod = req.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
                priMethod.Invoke(req.Headers, new[] { "Date", date });

                req.Headers.Add("Authorization", authHeader);
                if (postData.Length > 0)
                {
                    req.ContentLength = postData.Length;
                    req.Timeout = 15000;
                    Stream outputStream = req.GetRequestStream();
                    outputStream.Write(postData, 0, postData.Length);
                    outputStream.Flush();
                    outputStream.Close();
                    try
                    {
                        res = (HttpWebResponse)req.GetResponse();
                        System.IO.Stream InputStream = res.GetResponseStream();
                        Encoding encoding = Encoding.GetEncoding("UTF-8");
                        StreamReader sr = new StreamReader(InputStream, encoding);
                        result = sr.ReadToEnd();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                else
                {
                    res = (HttpWebResponse)req.GetResponse();
                    System.IO.Stream InputStream = res.GetResponseStream();
                    Encoding encoding = Encoding.GetEncoding("UTF-8");
                    StreamReader sr = new StreamReader(InputStream, encoding);
                    result = sr.ReadToEnd();
                    sr.Close();
                }
            }
            return result;
        }

        static void Main(string[] args)
        {
            String imgUrl1 = "http://pic.hnjsrcw.com/cam_entry/20180511/20391905371813208.jpg";
            String imgUrl2 = "http://pic.hnjsrcw.com/cam_entry/20180511/20391905371813208.jpg";

            string body = "{\"type\":0,\"image_url_1\":\"" + imgUrl1 + "\",\"image_url_2\":\"" + imgUrl2 + "\"}";

            try
            {
                string result = SendVerifyPost(body, "your Access Key ID", "your Access Key Secret");
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
输出结果:
{"confidence":99.99996948242188,"thresholds":[61.0,69.0,75.0],"rectA":[97,45,102,180],"rectB":[97,45,102,180],"errno":0,"request_id":"430dff94-3877-4c7d-92ae-70a0a98ba0a9"}

查看公众号文章

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值