|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Net.Http.Headers; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetThumbnail |
| 8 | +{ |
| 9 | + using Newtonsoft.Json.Linq; |
| 10 | + |
| 11 | + class Program |
| 12 | + { |
| 13 | + public const string subscriptionKey = "<your training key here>"; //Insert your Cognitive Services subscription key here |
| 14 | + public const string endpoint = "https://westus.api.cognitive.microsoft.com"; // You must use the same Azure region that you generated your subscription keys for. Free trial subscription keys are generated in the westus region. |
| 15 | + |
| 16 | + static void Main(string[] args) |
| 17 | + { |
| 18 | + GetThumbnailSample.RunAsync(endpoint, subscriptionKey).Wait(5000); |
| 19 | + |
| 20 | + Console.WriteLine("\nPress ENTER to exit."); |
| 21 | + Console.ReadLine(); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public class GetThumbnailSample |
| 26 | + { |
| 27 | + public static async Task RunAsync(string endpoint, string key) |
| 28 | + { |
| 29 | + Console.WriteLine("Get thumbnail of specific size in images:"); |
| 30 | + |
| 31 | + string imageFilePath = @"Images\objects.jpg"; // See this repo's readme.md for info on how to get these images. Alternatively, you can just set the path to any appropriate image on your machine. |
| 32 | + string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/celebrities.jpg"; |
| 33 | + |
| 34 | + await GetThumbnailFromStreamAsync(imageFilePath, endpoint, key, 50, 60, "."); |
| 35 | + await GetThumbnailFromUrlAsync(remoteImageUrl, endpoint, key, 50, 60, "."); |
| 36 | + } |
| 37 | + |
| 38 | + static async Task GetThumbnailFromStreamAsync(string imageFilePath, string endpoint, string subscriptionKey, int width, int height, string localSavePath) |
| 39 | + { |
| 40 | + if (!File.Exists(imageFilePath)) |
| 41 | + { |
| 42 | + Console.WriteLine("\nInvalid file path"); |
| 43 | + return; |
| 44 | + } |
| 45 | + try |
| 46 | + { |
| 47 | + HttpClient client = new HttpClient(); |
| 48 | + |
| 49 | + // Request headers. |
| 50 | + client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); |
| 51 | + string uriBase = $"{endpoint}/vision/v2.0/generateThumbnail"; |
| 52 | + string requestParameters = $"width={width}&height={height}&smartCropping=true"; |
| 53 | + // Assemble the URI for the REST API method. |
| 54 | + string uri = uriBase + "?" + requestParameters; |
| 55 | + |
| 56 | + // Read the contents of the specified local image into a byte array. |
| 57 | + byte[] byteData = GetImageAsByteArray(imageFilePath); |
| 58 | + // Add the byte array as an octet stream to the request body. |
| 59 | + using (ByteArrayContent content = new ByteArrayContent(byteData)) |
| 60 | + { |
| 61 | + // This example uses the "application/octet-stream" content type. |
| 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 | + // Asynchronously call the REST API method. |
| 66 | + HttpResponseMessage response = await client.PostAsync(uri, content); |
| 67 | + if (response.IsSuccessStatusCode) |
| 68 | + { |
| 69 | + //Display the response |
| 70 | + Console.WriteLine("\nResponse:\n{0}", response); |
| 71 | + //Get the thumbnail image to save |
| 72 | + byte[] thumbnailImageData = await response.Content.ReadAsByteArrayAsync(); |
| 73 | + //Save the thumbnail image. This will overwrite existing images at the path |
| 74 | + string imageName = Path.GetFileName(imageFilePath); |
| 75 | + string thumbnailFilePath = Path.Combine(localSavePath, imageName.Insert(imageName.Length - 4, "_thumb")); |
| 76 | + File.WriteAllBytes(thumbnailFilePath, thumbnailImageData); |
| 77 | + Console.WriteLine("Saved the image to {0}\n", thumbnailFilePath); |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + // Display the JSON error data. |
| 82 | + string errorString = await response.Content.ReadAsStringAsync(); |
| 83 | + Console.WriteLine("\n\nResponse:\n{0}\n", JToken.Parse(errorString).ToString()); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + catch (Exception e) |
| 88 | + { |
| 89 | + Console.WriteLine("\n" + e.Message); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + static byte[] GetImageAsByteArray(string imageFilePath) |
| 94 | + { |
| 95 | + // Open a read-only file stream for the specified file. |
| 96 | + using (FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read)) |
| 97 | + { |
| 98 | + // Read the file's contents into a byte array. |
| 99 | + BinaryReader binaryReader = new BinaryReader(fileStream); |
| 100 | + return binaryReader.ReadBytes((int)fileStream.Length); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + static async Task GetThumbnailFromUrlAsync(string imageUrl, string endpoint, string subscriptionKey, int width, int height, string localSavePath) |
| 105 | + { |
| 106 | + if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute)) |
| 107 | + { |
| 108 | + Console.WriteLine("\nInvalid remote image url:\n{0} \n", imageUrl); |
| 109 | + return; |
| 110 | + } |
| 111 | + try |
| 112 | + { |
| 113 | + HttpClient client = new HttpClient(); |
| 114 | + // Request headers. |
| 115 | + client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); |
| 116 | + string uriBase = $"{endpoint}/vision/v2.0/generateThumbnail"; |
| 117 | + string requestParameters = $"width={width}&height={height}&smartCropping=true"; |
| 118 | + string uri = uriBase + "?" + requestParameters; |
| 119 | + Console.WriteLine(uri); |
| 120 | + |
| 121 | + string requestBody = " {\"url\":\"" + imageUrl + "\"}"; |
| 122 | + var content = new StringContent(requestBody); |
| 123 | + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); |
| 124 | + |
| 125 | + // Post the request and display the result |
| 126 | + HttpResponseMessage response = await client.PostAsync(uri, content); |
| 127 | + if (response.IsSuccessStatusCode) |
| 128 | + { |
| 129 | + Console.WriteLine("\nResponse:\n{0}", response); |
| 130 | + //Get the thumbnail image to save |
| 131 | + byte[] thumbnailImageData = await response.Content.ReadAsByteArrayAsync(); |
| 132 | + //Save the thumbnail image. This will overwrite existing images at the path |
| 133 | + string imageName = Path.GetFileName(imageUrl); |
| 134 | + string thumbnailFilePath = Path.Combine(localSavePath, imageName.Insert(imageName.Length - 4, "_thumb")); |
| 135 | + File.WriteAllBytes(thumbnailFilePath, thumbnailImageData); |
| 136 | + Console.WriteLine("Saved the thumbnail image from URL to {0}\n", thumbnailFilePath); |
| 137 | + } |
| 138 | + else |
| 139 | + { |
| 140 | + // Display the JSON error data. |
| 141 | + string errorString = await response.Content.ReadAsStringAsync(); |
| 142 | + Console.WriteLine("\n\nResponse:\n{0}\n", JToken.Parse(errorString).ToString()); |
| 143 | + } |
| 144 | + } |
| 145 | + catch (Exception e) |
| 146 | + { |
| 147 | + Console.WriteLine("\n" + e.Message); |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | +} |
0 commit comments