人脸识别 API C# 示例代码

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

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

于是今天有了:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Reflection;  
  7. using System.Security.Cryptography;  
  8. using System.Text;  
  9.   
  10. namespace AliFace  
  11. {  
  12.     class Program  
  13.     {  
  14.         /// <summary>  
  15.         /// 计算MD5+BASE64  
  16.         /// </summary>  
  17.         /// <param name="s"></param>  
  18.         /// <returns></returns>  
  19.         public static String MD5Base64(String s)  
  20.         {  
  21.             if (s == null)  
  22.                 return null;  
  23.   
  24.             MD5 md5 = new MD5CryptoServiceProvider();  
  25.             byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(s));  
  26.   
  27.             return Convert.ToBase64String(result);  
  28.         }  
  29.           
  30.         /// <summary>  
  31.         /// 计算 HMAC-SHA1  
  32.         /// </summary>  
  33.         /// <param name="data"></param>  
  34.         /// <param name="key"></param>  
  35.         /// <returns></returns>  
  36.         public static String HMACSha1(String data, String key)  
  37.         {  
  38.             String result;  
  39.             try  
  40.             {  
  41.                 HMACSHA1 hmac = new HMACSHA1()  
  42.                 {  
  43.                     Key = Encoding.Default.GetBytes(key)  
  44.                 };  
  45.   
  46.                 byte[] rawHmac = hmac.ComputeHash(Encoding.Default.GetBytes(data));  
  47.                 result = Convert.ToBase64String(rawHmac);  
  48.             }  
  49.             catch (Exception e)  
  50.             {  
  51.                 throw new Exception("Failed to generate HMAC : " + e.Message);  
  52.             }  
  53.             return result;  
  54.         }  
  55.           
  56.         /// <summary>  
  57.         /// GMT 时间格式  
  58.         /// </summary>  
  59.         /// <param name="date"></param>  
  60.         /// <returns></returns>  
  61.         public static String toGMTString(DateTime date)  
  62.         {  
  63.             return date.ToString("r");  
  64.         }  
  65.   
  66.         /// <summary>  
  67.         /// 阿里人像比对接口地址  
  68.         /// </summary>  
  69.         public static string VerifyURL = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";  
  70.   
  71.         /// <summary>  
  72.         /// 发送 Post 请求  
  73.         /// </summary>  
  74.         /// <param name="body"></param>  
  75.         /// <param name="ak_id"></param>  
  76.         /// <param name="ak_secret"></param>  
  77.         /// <returns></returns>  
  78.         public static String SendVerifyPost(String body, String ak_id, String ak_secret)  
  79.         {  
  80.             // https 访问需要设置  ************************************************ 需要的  
  81.             ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;  
  82.   
  83.             String method = "POST";  
  84.             String accept = "application/json";  
  85.             String content_type = "application/json";  
  86.             String path = "/face/verify";  
  87.             String date = toGMTString(DateTime.Now);  
  88.             // 1.对body做MD5+BASE64加密  
  89.             String bodyMd5 = MD5Base64(body);  
  90.             String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"  
  91.                     + path;  
  92.             // 2.计算 HMAC-SHA1  
  93.             String signature = HMACSha1(stringToSign, ak_secret);  
  94.             String authHeader = "Dataplus " + ak_id + ":" + signature;  
  95.   
  96.             byte[] postData = Encoding.Default.GetBytes(body);  
  97.   
  98.   
  99.             string result = "";  
  100.             HttpWebRequest req = WebRequest.Create(VerifyURL) as HttpWebRequest;  
  101.             HttpWebResponse res = null;  
  102.             if (req != null)  
  103.             {  
  104.                 req.Method = method;  
  105.                 req.Accept = accept;  
  106.                 req.ContentType = content_type;  
  107.   
  108.                 // Date 参数不可直接设置,使用Header.Add 会报错    ************************************************ 需要的  
  109.                 MethodInfo priMethod = req.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);  
  110.                 priMethod.Invoke(req.Headers, new[] { "Date", date });  
  111.   
  112.                 req.Headers.Add("Authorization", authHeader);  
  113.                 if (postData.Length > 0)  
  114.                 {  
  115.                     req.ContentLength = postData.Length;  
  116.                     req.Timeout = 15000;  
  117.                     Stream outputStream = req.GetRequestStream();  
  118.                     outputStream.Write(postData, 0, postData.Length);  
  119.                     outputStream.Flush();  
  120.                     outputStream.Close();  
  121.                     try  
  122.                     {  
  123.                         res = (HttpWebResponse)req.GetResponse();  
  124.                         System.IO.Stream InputStream = res.GetResponseStream();  
  125.                         Encoding encoding = Encoding.GetEncoding("UTF-8");  
  126.                         StreamReader sr = new StreamReader(InputStream, encoding);  
  127.                         result = sr.ReadToEnd();  
  128.                     }  
  129.                     catch (Exception ex)  
  130.                     {  
  131.                     }  
  132.                 }  
  133.                 else  
  134.                 {  
  135.                     res = (HttpWebResponse)req.GetResponse();  
  136.                     System.IO.Stream InputStream = res.GetResponseStream();  
  137.                     Encoding encoding = Encoding.GetEncoding("UTF-8");  
  138.                     StreamReader sr = new StreamReader(InputStream, encoding);  
  139.                     result = sr.ReadToEnd();  
  140.                     sr.Close();  
  141.                 }  
  142.             }  
  143.             return result;  
  144.         }  
  145.   
  146.         static void Main(string[] args)  
  147.         {  
  148.             String imgUrl1 = "http://pic.hnjsrcw.com/cam_entry/20180511/20391905371813208.jpg";  
  149.             String imgUrl2 = "http://pic.hnjsrcw.com/cam_entry/20180511/20391905371813208.jpg";  
  150.   
  151.             string body = "{\"type\":0,\"image_url_1\":\"" + imgUrl1 + "\",\"image_url_2\":\"" + imgUrl2 + "\"}";  
  152.   
  153.             try  
  154.             {  
  155.                 string result = SendVerifyPost(body, "your Access Key ID""your Access Key Secret");  
  156.                 Console.WriteLine(result);  
  157.             }  
  158.             catch (Exception e)  
  159.             {  
  160.                 Console.WriteLine(e.Message);  
  161.             }  
  162.         }  
  163.     }  
  164. }  
输出结果:
[javascript]  view plain  copy
  1. {"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"}  

猜你喜欢

转载自blog.csdn.net/qq_41118173/article/details/80308360