c#调用阿里云实现图像识别,图像打标,人脸识别等
电脑版发表于:2020/2/17 21:40
随便创建一个类存放你的ak_id,ak_secret方便测试
public class SecretTools { public static string ak_id = "your ak_id "; public static string ak_secret = "your secret"; }
调用的代码:
public ActionResult Index() { string url = "https://dtplus-cn-shanghai.data.aliyuncs.com/image/tag"; //准备需要的参数 string method = "POST"; string accept = "application/json"; string contentType = accept; string date = DateTime.UtcNow.GetDateTimeFormats('r')[0].ToString(); //body var bodyobj = new { type = 0, image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581956240165&di=0984096776f9a34597df420f2ff37d1c&imgtype=0&src=http%3A%2F%2F06imgmini.eastday.com%2Fmobile%2F20180827%2F20180827230103_4b8017aa5fe754c1e44960747e375068_15.jpeg" }; string bodyjsonStr = JsonConvert.SerializeObject(bodyobj); byte[] data = System.Text.Encoding.ASCII.GetBytes(bodyjsonStr); byte[] md5 = new MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(bodyjsonStr)); string bodyMd5 = Convert.ToBase64String(md5); //signature,authHeader string stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + contentType + "\n" + date + "\n" + "/image/tag"; var md5code = new HMACSHA1(System.Text.Encoding.UTF8.GetBytes(SecretTools.ak_secret)).ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)); var signature = Convert.ToBase64String(md5code); string authHeader = "Dataplus " + SecretTools.ak_id + ":" + signature; //调用接口 WebRequest webRequest = WebRequest.Create(url); webRequest.Method = method; webRequest.ContentType = contentType; //写入body webRequest.GetRequestStream().Write(data, 0, data.Length); //按照阿里云文档说明提供headers参数设置(注意:这种设置方法会报:必须使用适当的属性或方法修改“Date”标头) //req.Headers.Add("Date", date); //req.Headers.Add("Authorization", authHeader); //req.Headers.Add("Accept", accept); //根据反射来给header提供需要的参数 MethodInfo methodInfo = webRequest.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic); methodInfo.Invoke(webRequest.Headers, new[] { "Date", date }); methodInfo.Invoke(webRequest.Headers, new[] { "Authorization", authHeader }); methodInfo.Invoke(webRequest.Headers, new[] { "Accept", accept }); //调用接口得到返回内容 System.IO.Stream stream = webRequest.GetResponse().GetResponseStream(); System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); string result = streamReader.ReadToEnd(); return View(); }
返回数据如下:这里调用的是图像识别中的图像打标接口,其他接口几乎一样修改参数即可
把调用接口的代码优化一下封装成一个方法
上面的方法太多了,不可能每次都写那么大一堆,封装一下我们调用就会方便很多了
public class AliAITools { public static string Invoke(string ak_id, string ak_secret, string url, string tag, string bodyjsonStr) { //准备需要的参数 string method = "POST"; string accept = "application/json"; string contentType = accept; string date = DateTime.UtcNow.GetDateTimeFormats('r')[0].ToString(); byte[] data = System.Text.Encoding.ASCII.GetBytes(bodyjsonStr); byte[] md5 = new MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(bodyjsonStr)); string bodyMd5 = Convert.ToBase64String(md5); //signature,authHeader string stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + contentType + "\n" + date + "\n" + tag; var md5code = new HMACSHA1(System.Text.Encoding.UTF8.GetBytes(ak_secret)).ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)); var signature = Convert.ToBase64String(md5code); string authHeader = "Dataplus " + ak_id + ":" + signature; //调用接口 WebRequest webRequest = WebRequest.Create(url); webRequest.Method = method; webRequest.ContentType = contentType; //写入body webRequest.GetRequestStream().Write(data, 0, data.Length); //按照阿里云文档说明提供headers参数设置(注意:这种设置方法会报:必须使用适当的属性或方法修改“Date”标头) //req.Headers.Add("Date", date); //req.Headers.Add("Authorization", authHeader); //req.Headers.Add("Accept", accept); //根据反射来给header提供需要的参数 MethodInfo methodInfo = webRequest.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic); methodInfo.Invoke(webRequest.Headers, new[] { "Date", date }); methodInfo.Invoke(webRequest.Headers, new[] { "Authorization", authHeader }); methodInfo.Invoke(webRequest.Headers, new[] { "Accept", accept }); //调用接口得到返回内容 System.IO.Stream stream = webRequest.GetResponse().GetResponseStream(); System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); string result = streamReader.ReadToEnd(); return result; } }
调用:这里我们为了区分一下调用图片识别中的场景识别试试
public ActionResult MageScene() { //构建参数 var body = new { type = 0, image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581958125820&di=385b135756592dfb5f98c14ac4a00a20&imgtype=0&src=http%3A%2F%2Fpix3.agoda.net%2FhotelImages%2F111%2F1115826%2F1115826_16051715300042404569.jpg" }; string bodyJsonStr = JsonConvert.SerializeObject(body); string url = "https://dtplus-cn-shanghai.data.aliyuncs.com/image/scene"; string result = AliAITools.Invoke(SecretTools.ak_id, SecretTools.ak_secret, url, "/image/scene", bodyJsonStr); return View(); }
可以看到很简洁代码会少很多
使用Base64的传递方式调用一下
public ActionResult MageSceneBase64() { //base64格式传输图片 var body = new { type = 1, content = getFileBase64("c://cc.jpg") }; string bodyJsonStr = JsonConvert.SerializeObject(body); string url = "https://dtplus-cn-shanghai.data.aliyuncs.com/image/scene"; string result = AliAITools.Invoke(SecretTools.ak_id, SecretTools.ak_secret, url, "/image/scene", bodyJsonStr); return View(); }
getFileBase64的方法贴一下:
public 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; }
至于其他同类型的接口我们可以自己修改一下参数即可完成调用
比如图片当然的人脸检测接口:
/// <summary> /// 人脸检测 /// </summary> /// <returns></returns> public ActionResult FaceDetect() { var body = new { type = 0, image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581961247078&di=360bd00e6abacceaa6e6e2d7c22c82bf&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn20%2F397%2Fw1200h797%2F20180723%2F2155-hftenhz1666262.jpg" }; string bodyJsonStr = JsonConvert.SerializeObject(body); string url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/detect"; string result = AliAITools.Invoke(SecretTools.ak_id, SecretTools.ak_secret, url, "/face/detect", bodyJsonStr); return View(); }
或者图片当中的人脸属性识别接口:
/// <summary> /// 人脸属性识别 /// </summary> /// <returns></returns> public ActionResult FaceAttribute() { var body = new { type = 0, image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581961247078&di=360bd00e6abacceaa6e6e2d7c22c82bf&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn20%2F397%2Fw1200h797%2F20180723%2F2155-hftenhz1666262.jpg" }; string bodyJsonStr = JsonConvert.SerializeObject(body); string url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute"; string result = AliAITools.Invoke(SecretTools.ak_id, SecretTools.ak_secret, url, "/face/attribute", bodyJsonStr); return View(); }