Skip to content

Commit 4b98cbc

Browse files
authored
Initial commit
1 parent c4cf8f5 commit 4b98cbc

File tree

1 file changed

+158
-0
lines changed

1 file changed

+158
-0
lines changed
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using System;
5+
using System.IO;
6+
using System.Net.Http;
7+
using System.Net.Http.Headers;
8+
using System.Text;
9+
10+
/* This sample uses the Azure Computer Vision API to analyze an image,
11+
* then retrieves its categories, color, description, and captions... in addition to some metadata.
12+
*/
13+
14+
namespace ComputerVisionSample
15+
{
16+
static class Program
17+
{
18+
// Add your Azure Computer Vision subscription key and endpoint to your environment variables
19+
public static string subscriptionKey = Environment.GetEnvironmentVariable("COMPUTER_VISION_SUBSCRIPTION_KEY");
20+
public static string uriBase = Environment.GetEnvironmentVariable("COMPUTER_VISION_ENDPOINT");
21+
22+
static void Main()
23+
{
24+
// Download an image from here:
25+
// https://github.com/Azure-Samples/cognitive-services-sample-data-files/tree/master/ComputerVision/Images
26+
// Or add your own image and put into your bin\Debug\netcoreapp3.0\Images folder.
27+
string imageFilePath = @"Images\objects.jpg";
28+
29+
// Execute the REST API call.
30+
MakeAnalysisRequest(imageFilePath);
31+
32+
Console.WriteLine("\nPlease wait a moment for the results to appear. Then, press Enter to exit...\n");
33+
Console.ReadLine();
34+
}
35+
36+
37+
/// <summary>
38+
/// Gets the analysis of the specified image file by using the Computer Vision REST API.
39+
/// </summary>
40+
/// <param name="imageFilePath">The image file.</param>
41+
static async void MakeAnalysisRequest(string imageFilePath)
42+
{
43+
HttpClient client = new HttpClient();
44+
45+
// Request headers.
46+
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
47+
48+
// Request parameters. A third optional parameter is "details".
49+
string requestParameters = "visualFeatures=Categories,Description,Color&language=en";
50+
51+
// Assemble the URI for the REST API Call.
52+
string uri = uriBase + "/vision/v2.0/analyze?" + requestParameters;
53+
54+
HttpResponseMessage response;
55+
56+
// Request body. Posts a locally stored JPEG image.
57+
byte[] byteData = GetImageAsByteArray(imageFilePath);
58+
59+
using (ByteArrayContent content = new ByteArrayContent(byteData))
60+
{
61+
// This example uses content type "application/octet-stream".
62+
// The other content types you can use are "application/json" and "multipart/form-data".
63+
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
64+
65+
// Execute the REST API call.
66+
response = await client.PostAsync(uri, content);
67+
68+
// Get the JSON response.
69+
string contentString = await response.Content.ReadAsStringAsync();
70+
71+
// Display the JSON response.
72+
Console.WriteLine("\nResponse:\n");
73+
Console.WriteLine(JsonPrettyPrint(contentString));
74+
}
75+
}
76+
77+
78+
/// <summary>
79+
/// Returns the contents of the specified file as a byte array.
80+
/// </summary>
81+
/// <param name="imageFilePath">The image file to read.</param>
82+
/// <returns>The byte array of the image data.</returns>
83+
static byte[] GetImageAsByteArray(string imageFilePath)
84+
{
85+
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
86+
BinaryReader binaryReader = new BinaryReader(fileStream);
87+
return binaryReader.ReadBytes((int)fileStream.Length);
88+
}
89+
90+
91+
/// <summary>
92+
/// Formats the given JSON string by adding line breaks and indents.
93+
/// </summary>
94+
/// <param name="json">The raw JSON string to format.</param>
95+
/// <returns>The formatted JSON string.</returns>
96+
static string JsonPrettyPrint(string json)
97+
{
98+
if (string.IsNullOrEmpty(json))
99+
return string.Empty;
100+
101+
json = json.Replace(Environment.NewLine, "").Replace("\t", "");
102+
103+
StringBuilder sb = new StringBuilder();
104+
bool quote = false;
105+
bool ignore = false;
106+
int offset = 0;
107+
int indentLength = 3;
108+
109+
foreach (char ch in json)
110+
{
111+
switch (ch)
112+
{
113+
case '"':
114+
if (!ignore) quote = !quote;
115+
break;
116+
case '\'':
117+
if (quote) ignore = !ignore;
118+
break;
119+
}
120+
121+
if (quote)
122+
sb.Append(ch);
123+
else
124+
{
125+
switch (ch)
126+
{
127+
case '{':
128+
case '[':
129+
sb.Append(ch);
130+
sb.Append(Environment.NewLine);
131+
sb.Append(new string(' ', ++offset * indentLength));
132+
break;
133+
case '}':
134+
case ']':
135+
sb.Append(Environment.NewLine);
136+
sb.Append(new string(' ', --offset * indentLength));
137+
sb.Append(ch);
138+
break;
139+
case ',':
140+
sb.Append(ch);
141+
sb.Append(Environment.NewLine);
142+
sb.Append(new string(' ', offset * indentLength));
143+
break;
144+
case ':':
145+
sb.Append(ch);
146+
sb.Append(' ');
147+
break;
148+
default:
149+
if (ch != ' ') sb.Append(ch);
150+
break;
151+
}
152+
}
153+
}
154+
155+
return sb.ToString().Trim();
156+
}
157+
}
158+
}

0 commit comments

Comments
 (0)