Skip to content

Commit

Permalink
Modifying an existing quickstart for consistency (#38)
Browse files Browse the repository at this point in the history
* Added GetThumbnail quickstart

* Updated readme

* Used Path inbuilt functions to replace clunky hardcoded line

* Updated Readme
  • Loading branch information
harishkrishnav authored and ChrisHMSFT committed Jul 12, 2019
1 parent 164d180 commit 9d7393e
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 5 deletions.
16 changes: 11 additions & 5 deletions dotnet/ComputerVision/ComputerVision.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.CognitiveSe
EndProject
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}"
EndProject
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}"
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}"
EndProject
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}"
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}"
EndProject
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}"
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}"
EndProject
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}"
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}"
EndProject
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}"
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}"
EndProject
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}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -63,6 +65,10 @@ Global
{C024B030-8CA9-4239-9C89-371B24E029CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C024B030-8CA9-4239-9C89-371B24E029CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C024B030-8CA9-4239-9C89-371B24E029CE}.Release|Any CPU.Build.0 = Release|Any CPU
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7D808D7-0294-471C-AD6A-C70626F97C21}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.0;net461;netstandard1.4</TargetFrameworks>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup>

</Project>
151 changes: 151 additions & 0 deletions dotnet/ComputerVision/GetThumbnail/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Microsoft.Azure.CognitiveServices.Samples.ComputerVision.GetThumbnail
{
using Newtonsoft.Json.Linq;

class Program
{
public const string subscriptionKey = "<your training key here>"; //Insert your Cognitive Services subscription key here
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.

static void Main(string[] args)
{
GetThumbnailSample.RunAsync(endpoint, subscriptionKey).Wait(5000);

Console.WriteLine("\nPress ENTER to exit.");
Console.ReadLine();
}
}

public class GetThumbnailSample
{
public static async Task RunAsync(string endpoint, string key)
{
Console.WriteLine("Get thumbnail of specific size in images:");

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.
string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/celebrities.jpg";

await GetThumbnailFromStreamAsync(imageFilePath, endpoint, key, 50, 60, ".");
await GetThumbnailFromUrlAsync(remoteImageUrl, endpoint, key, 50, 60, ".");
}

static async Task GetThumbnailFromStreamAsync(string imageFilePath, string endpoint, string subscriptionKey, int width, int height, string localSavePath)
{
if (!File.Exists(imageFilePath))
{
Console.WriteLine("\nInvalid file path");
return;
}
try
{
HttpClient client = new HttpClient();

// Request headers.
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
string uriBase = $"{endpoint}/vision/v2.0/generateThumbnail";
string requestParameters = $"width={width}&height={height}&smartCropping=true";
// Assemble the URI for the REST API method.
string uri = uriBase + "?" + requestParameters;

// Read the contents of the specified local image into a byte array.
byte[] byteData = GetImageAsByteArray(imageFilePath);
// Add the byte array as an octet stream to the request body.
using (ByteArrayContent content = new ByteArrayContent(byteData))
{
// This example uses the "application/octet-stream" content type.
// The other content types you can use are "application/json" and "multipart/form-data".
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

// Asynchronously call the REST API method.
HttpResponseMessage response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
//Display the response
Console.WriteLine("\nResponse:\n{0}", response);
//Get the thumbnail image to save
byte[] thumbnailImageData = await response.Content.ReadAsByteArrayAsync();
//Save the thumbnail image. This will overwrite existing images at the path
string imageName = Path.GetFileName(imageFilePath);
string thumbnailFilePath = Path.Combine(localSavePath, imageName.Insert(imageName.Length - 4, "_thumb"));
File.WriteAllBytes(thumbnailFilePath, thumbnailImageData);
Console.WriteLine("Saved the image to {0}\n", thumbnailFilePath);
}
else
{
// Display the JSON error data.
string errorString = await response.Content.ReadAsStringAsync();
Console.WriteLine("\n\nResponse:\n{0}\n", JToken.Parse(errorString).ToString());
}
}
}
catch (Exception e)
{
Console.WriteLine("\n" + e.Message);
}
}

static byte[] GetImageAsByteArray(string imageFilePath)
{
// Open a read-only file stream for the specified file.
using (FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
{
// Read the file's contents into a byte array.
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}

static async Task GetThumbnailFromUrlAsync(string imageUrl, string endpoint, string subscriptionKey, int width, int height, string localSavePath)
{
if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
{
Console.WriteLine("\nInvalid remote image url:\n{0} \n", imageUrl);
return;
}
try
{
HttpClient client = new HttpClient();
// Request headers.
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
string uriBase = $"{endpoint}/vision/v2.0/generateThumbnail";
string requestParameters = $"width={width}&height={height}&smartCropping=true";
string uri = uriBase + "?" + requestParameters;
Console.WriteLine(uri);

string requestBody = " {\"url\":\"" + imageUrl + "\"}";
var content = new StringContent(requestBody);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

// Post the request and display the result
HttpResponseMessage response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\nResponse:\n{0}", response);
//Get the thumbnail image to save
byte[] thumbnailImageData = await response.Content.ReadAsByteArrayAsync();
//Save the thumbnail image. This will overwrite existing images at the path
string imageName = Path.GetFileName(imageUrl);
string thumbnailFilePath = Path.Combine(localSavePath, imageName.Insert(imageName.Length - 4, "_thumb"));
File.WriteAllBytes(thumbnailFilePath, thumbnailImageData);
Console.WriteLine("Saved the thumbnail image from URL to {0}\n", thumbnailFilePath);
}
else
{
// Display the JSON error data.
string errorString = await response.Content.ReadAsStringAsync();
Console.WriteLine("\n\nResponse:\n{0}\n", JToken.Parse(errorString).ToString());
}
}
catch (Exception e)
{
Console.WriteLine("\n" + e.Message);
}
}
}
}
1 change: 1 addition & 0 deletions dotnet/ComputerVision/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ The projects in this code are quickstarts that show how to use Computer Vision R
| RecognizeDomainSpecificContent| Project that recognizes celebrities and landmarks in an image |
| RecognizeText| Project that recognizes text in an image |
| TagImage| Project to tag an image|
| GetThumbnail | Gets a recommended thumbnail for an image given a target size |
| ComputerVision.sln | The Visual Studio solution with the above projects|
| readme.md | This README file. |

Expand Down

0 comments on commit 9d7393e

Please sign in to comment.