Skip to content

Commit 9d7393e

Browse files
harishkrishnavChrisHMSFT
authored andcommitted
Modifying an existing quickstart for consistency (#38)
* Added GetThumbnail quickstart * Updated readme * Used Path inbuilt functions to replace clunky hardcoded line * Updated Readme
1 parent 164d180 commit 9d7393e

File tree

4 files changed

+175
-5
lines changed

4 files changed

+175
-5
lines changed

dotnet/ComputerVision/ComputerVision.sln

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,17 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveSe
1111
EndProject
1212
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.OCR", "OCR\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.OCR.csproj", "{F3F98FCD-728E-424C-A66E-64F5F0870298}"
1313
EndProject
14-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage", "DescribeImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage.csproj", "{236A621F-1422-4F11-A1DB-63A98FA81964}"
14+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage", "DescribeImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.DescribeImage.csproj", "{236A621F-1422-4F11-A1DB-63A98FA81964}"
1515
EndProject
16-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetAreaOfInterest", "GetAreaOfInterest\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetAreaOfInterest.csproj", "{13CD735C-6C88-4C7D-9084-13924F9012DF}"
16+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetAreaOfInterest", "GetAreaOfInterest\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetAreaOfInterest.csproj", "{13CD735C-6C88-4C7D-9084-13924F9012DF}"
1717
EndProject
18-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.TagImage", "TagImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.TagImage.csproj", "{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}"
18+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.TagImage", "TagImage\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.TagImage.csproj", "{6F9E7415-FD2A-475C-A668-DB83D29DCBAE}"
1919
EndProject
20-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeDomainSpecificContent", "RecognizeDomainSpecificContent\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeDomainSpecificContent.csproj", "{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}"
20+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeDomainSpecificContent", "RecognizeDomainSpecificContent\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeDomainSpecificContent.csproj", "{AFDFD5AC-2E2D-46C0-A25D-0AF09C6A89D8}"
2121
EndProject
22-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeText", "RecognizeText\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeText.csproj", "{C024B030-8CA9-4239-9C89-371B24E029CE}"
22+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeText", "RecognizeText\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.RecognizeText.csproj", "{C024B030-8CA9-4239-9C89-371B24E029CE}"
23+
EndProject
24+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetThumbnail", "GetThumbnail\Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetThumbnail.csproj", "{E7D808D7-0294-471C-AD6A-C70626F97C21}"
2325
EndProject
2426
Global
2527
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -63,6 +65,10 @@ Global
6365
{C024B030-8CA9-4239-9C89-371B24E029CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
6466
{C024B030-8CA9-4239-9C89-371B24E029CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
6567
{C024B030-8CA9-4239-9C89-371B24E029CE}.Release|Any CPU.Build.0 = Release|Any CPU
68+
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
69+
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Debug|Any CPU.Build.0 = Debug|Any CPU
70+
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Release|Any CPU.ActiveCfg = Release|Any CPU
71+
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Release|Any CPU.Build.0 = Release|Any CPU
6672
EndGlobalSection
6773
GlobalSection(SolutionProperties) = preSolution
6874
HideSolutionNode = FALSE
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFrameworks>netcoreapp2.0;net461;netstandard1.4</TargetFrameworks>
6+
</PropertyGroup>
7+
8+
<ItemGroup>
9+
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
10+
</ItemGroup>
11+
12+
</Project>
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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+
}

dotnet/ComputerVision/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ The projects in this code are quickstarts that show how to use Computer Vision R
2424
| RecognizeDomainSpecificContent| Project that recognizes celebrities and landmarks in an image |
2525
| RecognizeText| Project that recognizes text in an image |
2626
| TagImage| Project to tag an image|
27+
| GetThumbnail | Gets a recommended thumbnail for an image given a target size |
2728
| ComputerVision.sln | The Visual Studio solution with the above projects|
2829
| readme.md | This README file. |
2930

0 commit comments

Comments
 (0)