|
| 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 HttpClientSample |
| 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 | + /// <summary> |
| 37 | + /// Gets the analysis of the specified image file by using the Computer Vision REST API. |
| 38 | + /// </summary> |
| 39 | + /// <param name="imageFilePath">The image file.</param> |
| 40 | + static async void MakeAnalysisRequest(string imageFilePath) |
| 41 | + { |
| 42 | + HttpClient client = new HttpClient(); |
| 43 | + |
| 44 | + // Request headers. |
| 45 | + client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); |
| 46 | + |
| 47 | + // Request parameters. A third optional parameter is "details". |
| 48 | + string requestParameters = "visualFeatures=Categories,Description,Color&language=en"; |
| 49 | + |
| 50 | + // Assemble the URI for the REST API Call. |
| 51 | + string uri = uriBase + "/vision/v2.0/analyze?" + requestParameters; |
| 52 | + |
| 53 | + HttpResponseMessage response; |
| 54 | + |
| 55 | + // Request body. Posts a locally stored JPEG image. |
| 56 | + byte[] byteData = GetImageAsByteArray(imageFilePath); |
| 57 | + |
| 58 | + using (ByteArrayContent content = new ByteArrayContent(byteData)) |
| 59 | + { |
| 60 | + // This example uses content type "application/octet-stream". |
| 61 | + // The other content types you can use are "application/json" and "multipart/form-data". |
| 62 | + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); |
| 63 | + |
| 64 | + // Execute the REST API call. |
| 65 | + response = await client.PostAsync(uri, content); |
| 66 | + |
| 67 | + // Get the JSON response. |
| 68 | + string contentString = await response.Content.ReadAsStringAsync(); |
| 69 | + |
| 70 | + // Display the JSON response. |
| 71 | + Console.WriteLine("\nResponse:\n"); |
| 72 | + Console.WriteLine(JsonPrettyPrint(contentString)); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + /// <summary> |
| 77 | + /// Returns the contents of the specified file as a byte array. |
| 78 | + /// </summary> |
| 79 | + /// <param name="imageFilePath">The image file to read.</param> |
| 80 | + /// <returns>The byte array of the image data.</returns> |
| 81 | + static byte[] GetImageAsByteArray(string imageFilePath) |
| 82 | + { |
| 83 | + FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read); |
| 84 | + BinaryReader binaryReader = new BinaryReader(fileStream); |
| 85 | + return binaryReader.ReadBytes((int)fileStream.Length); |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | + /// <summary> |
| 90 | + /// Formats the given JSON string by adding line breaks and indents. |
| 91 | + /// </summary> |
| 92 | + /// <param name="json">The raw JSON string to format.</param> |
| 93 | + /// <returns>The formatted JSON string.</returns> |
| 94 | + static string JsonPrettyPrint(string json) |
| 95 | + { |
| 96 | + if (string.IsNullOrEmpty(json)) |
| 97 | + return string.Empty; |
| 98 | + |
| 99 | + json = json.Replace(Environment.NewLine, "").Replace("\t", ""); |
| 100 | + |
| 101 | + StringBuilder sb = new StringBuilder(); |
| 102 | + bool quote = false; |
| 103 | + bool ignore = false; |
| 104 | + int offset = 0; |
| 105 | + int indentLength = 3; |
| 106 | + |
| 107 | + foreach (char ch in json) |
| 108 | + { |
| 109 | + switch (ch) |
| 110 | + { |
| 111 | + case '"': |
| 112 | + if (!ignore) quote = !quote; |
| 113 | + break; |
| 114 | + case '\'': |
| 115 | + if (quote) ignore = !ignore; |
| 116 | + break; |
| 117 | + } |
| 118 | + |
| 119 | + if (quote) |
| 120 | + sb.Append(ch); |
| 121 | + else |
| 122 | + { |
| 123 | + switch (ch) |
| 124 | + { |
| 125 | + case '{': |
| 126 | + case '[': |
| 127 | + sb.Append(ch); |
| 128 | + sb.Append(Environment.NewLine); |
| 129 | + sb.Append(new string(' ', ++offset * indentLength)); |
| 130 | + break; |
| 131 | + case '}': |
| 132 | + case ']': |
| 133 | + sb.Append(Environment.NewLine); |
| 134 | + sb.Append(new string(' ', --offset * indentLength)); |
| 135 | + sb.Append(ch); |
| 136 | + break; |
| 137 | + case ',': |
| 138 | + sb.Append(ch); |
| 139 | + sb.Append(Environment.NewLine); |
| 140 | + sb.Append(new string(' ', offset * indentLength)); |
| 141 | + break; |
| 142 | + case ':': |
| 143 | + sb.Append(ch); |
| 144 | + sb.Append(' '); |
| 145 | + break; |
| 146 | + default: |
| 147 | + if (ch != ' ') sb.Append(ch); |
| 148 | + break; |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + return sb.ToString().Trim(); |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments