· 6 years ago · Jan 23, 2020, 05:34 PM
1using System;
2using System.IO;
3using System.Net.Http;
4using System.Net.Http.Headers;
5using System.Text;
6
7namespace API
8{
9 static class Program
10 {
11 // Replace <Subscription Key> with your valid subscription key.
12 const string subscriptionKey = "<Subscription Key>";
13
14 // replace <myresourcename> with the string found in your endpoint URL
15 const string uriBase =
16 "https://<myresourcename>.cognitive.microsoft.com/face/v1.0/detect";
17
18
19 static void Main(string[] args)
20 {
21
22 // Get the path and filename to process from the user.
23 Console.WriteLine("Detect faces:");
24 Console.Write(
25 "Enter the path to an image with faces that you wish to analyze: ");
26 string imageFilePath = Console.ReadLine();
27
28 if (File.Exists(imageFilePath))
29 {
30 try
31 {
32 MakeAnalysisRequest(imageFilePath);
33 Console.WriteLine("\nWait a moment for the results to appear.\n");
34 }
35 catch (Exception e)
36 {
37 Console.WriteLine("\n" + e.Message + "\nPress Enter to exit...\n");
38 }
39 }
40 else
41 {
42 Console.WriteLine("\nInvalid file path.\nPress Enter to exit...\n");
43 }
44 Console.ReadLine();
45 }
46
47
48 // Gets the analysis of the specified image by using the Face REST API.
49 static async void MakeAnalysisRequest(string imageFilePath)
50 {
51 HttpClient client = new HttpClient();
52
53 // Request headers.
54 client.DefaultRequestHeaders.Add(
55 "Ocp-Apim-Subscription-Key", subscriptionKey);
56
57 // Request parameters. A third optional parameter is "details".
58 string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
59 "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
60 "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
61
62 // Assemble the URI for the REST API Call.
63 string uri = uriBase + "?" + requestParameters;
64
65 HttpResponseMessage response;
66
67 // Request body. Posts a locally stored JPEG image.
68 byte[] byteData = GetImageAsByteArray(imageFilePath);
69
70 using (ByteArrayContent content = new ByteArrayContent(byteData))
71 {
72 // This example uses content type "application/octet-stream".
73 // The other content types you can use are "application/json"
74 // and "multipart/form-data".
75 content.Headers.ContentType =
76 new MediaTypeHeaderValue("application/octet-stream");
77
78 // Execute the REST API call.
79 response = await client.PostAsync(uri, content);
80
81 // Get the JSON response.
82 string contentString = await response.Content.ReadAsStringAsync();
83
84 // Display the JSON response.
85 Console.WriteLine("\nResponse:\n");
86 Console.WriteLine(JsonPrettyPrint(contentString));
87 Console.WriteLine("\nPress Enter to exit...");
88 }
89
90
91 }
92 // Returns the contents of the specified file as a byte array.
93 static byte[] GetImageAsByteArray(string imageFilePath)
94 {
95 using (FileStream fileStream =
96 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
97 {
98 BinaryReader binaryReader = new BinaryReader(fileStream);
99 return binaryReader.ReadBytes((int)fileStream.Length);
100 }
101 }
102 // Formats the given JSON string by adding line breaks and indents.
103 static string JsonPrettyPrint(string json)
104 {
105 if (string.IsNullOrEmpty(json))
106 return string.Empty;
107
108 json = json.Replace(Environment.NewLine, "").Replace("\t", "");
109
110 StringBuilder sb = new StringBuilder();
111 bool quote = false;
112 bool ignore = false;
113 int offset = 0;
114 int indentLength = 3;
115
116 foreach (char ch in json)
117 {
118 switch (ch)
119 {
120 case '"':
121 if (!ignore) quote = !quote;
122 break;
123 case '\'':
124 if (quote) ignore = !ignore;
125 break;
126 }
127
128 if (quote)
129 sb.Append(ch);
130 else
131 {
132 switch (ch)
133 {
134 case '{':
135 case '[':
136 sb.Append(ch);
137 sb.Append(Environment.NewLine);
138 sb.Append(new string(' ', ++offset * indentLength));
139 break;
140 case '}':
141 case ']':
142 sb.Append(Environment.NewLine);
143 sb.Append(new string(' ', --offset * indentLength));
144 sb.Append(ch);
145 break;
146 case ',':
147 sb.Append(ch);
148 sb.Append(Environment.NewLine);
149 sb.Append(new string(' ', offset * indentLength));
150 break;
151 case ':':
152 sb.Append(ch);
153 sb.Append(' ');
154 break;
155 default:
156 if (ch != ' ') sb.Append(ch);
157 break;
158 }
159 }
160 }
161
162 return sb.ToString().Trim();
163 }
164 }
165}