Face Recognition Using Microsoft Vision API

Using computer vision API, you can analyze an image. To analyze an image, you can either upload an Image or specify an Image URL.


  1. A subscription keys. To get a subscription key go to this link: Obtaining Subscription Keys.
  2. Need an IDE for example: Visual Studio 2017

Step to create a sample application:

  1. Open visual studio and create a console application
  2. Replace content of the Program.cs file by the following code.
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace FaceDemo
    class Program
        //NOTE: To create subscription key
        //To create subscription key. Go to azure portal search emotion and create face key

        // Replace  with your valid subscription key.
        //It actually not subscription key. Its cognitive-face01 Key1
        //To find subscriptionkey, go to Home->CognitiveFace01->ManageKeys (KEY 1)'
        const string subscriptionKey = "";

        // NOTE: You must use the same region in your REST call as you used to
        // obtain your subscription keys. For example, if you obtained your
        // subscription keys from westus, replace "westcentralus" in the URL
        // below with "westus".
        // Free trial subscription keys are generated in the "westus" region.
        // If you use a free trial subscription key, you shouldn't need to change
        // this region.

        //To find uriBase, go to Home->CognitiveFace01->EndPoint + '/detect'
        const string uriBase =

        static void Main(string[] args)
            // Get the path and filename to process from the user.
            Console.WriteLine("Detect faces:");
                "Enter the path to an image with faces that you wish to analyze: ");

            //Image path you want to detect
            string imageFilePath = @"D:\Projects\Github\ms-cognitive\FaceDemo\Images\mahedee-buet.jpg";


            if (File.Exists(imageFilePath))
                    Console.WriteLine("\nWait a moment for the results to appear.\n");
                catch (Exception e)
                    Console.WriteLine("\n" + e.Message + "\nPress Enter to exit...\n");
                Console.WriteLine("\nInvalid file path.\nPress Enter to exit...\n");

        // Gets the analysis of the specified image by using the Face REST API.
        static async void MakeAnalysisRequest(string imageFilePath)
            HttpClient client = new HttpClient();

            // Request headers.
                "Ocp-Apim-Subscription-Key", subscriptionKey);

            // Request parameters. A third optional parameter is "details".
            string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
                "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +

            // Assemble the URI for the REST API Call.
            string uri = uriBase + "?" + requestParameters;

            HttpResponseMessage response;

            // Request body. Posts a locally stored JPEG image.
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            using (ByteArrayContent content = new ByteArrayContent(byteData))
                // This example uses content type "application/octet-stream".
                // The other content types you can use are "application/json"
                // and "multipart/form-data".
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                // Execute the REST API call.
                response = await client.PostAsync(uri, content);

                // Get the JSON response.
                string contentString = await response.Content.ReadAsStringAsync();

                // Display the JSON response.
                Console.WriteLine("\nPress Enter to exit...");

        // Returns the contents of the specified file as a byte array.
        static byte[] GetImageAsByteArray(string imageFilePath)
            using (FileStream fileStream =
                new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
                BinaryReader binaryReader = new BinaryReader(fileStream);
                return binaryReader.ReadBytes((int)fileStream.Length);

        // Formats the given JSON string by adding line breaks and indents.
        //Json Perser

        static string JsonPrettyPrint(string json)
            if (string.IsNullOrEmpty(json))
                return string.Empty;

            json = json.Replace(Environment.NewLine, "").Replace("\t", "");

            StringBuilder sb = new StringBuilder();
            bool quote = false;
            bool ignore = false;
            int offset = 0;
            int indentLength = 3;

            foreach (char ch in json)
                switch (ch)
                    case '"':
                        if (!ignore) quote = !quote;
                    case '\'':
                        if (quote) ignore = !ignore;

                if (quote)
                    switch (ch)
                        case '{':
                        case '[':
                            sb.Append(new string(' ', ++offset * indentLength));
                        case '}':
                        case ']':
                            sb.Append(new string(' ', --offset * indentLength));
                        case ',':
                            sb.Append(new string(' ', offset * indentLength));
                        case ':':
                            sb.Append(' ');
                            if (ch != ' ') sb.Append(ch);

            return sb.ToString().Trim();

3. Replace your subscription key
4. Replace your image path

Now you will see the following output of the given image. Output describes: Face attribute, gender, age, emotion etc.

Leave a Reply

Your email address will not be published. Required fields are marked *