Create thumbnails for an asset in Microsoft Azure Media Services

When we’re working with media we have to know a very important feature: creating thumbnails because It will be easy for us to recognize the content of the video. Within Microsoft Azure Media Services we can create these images through the processor Windows Azure Media Encoder, also used for encoding files:

using Microsoft.WindowsAzure.MediaServices.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Thumbnails
{
    class Program
    {
        static void Main(string[] args)
        {
            //0. Constants
            const string AssetName = "Frozen-mp4-Source";
            const string AccountName = "[ACCOUNT_NAME]";
            const string AccountKey = "[ACCOUNT_KEY]";
            //1. Nuget: Install-Package windowsazure.mediaservices
            //2. Nuget: Install-Package windowsazure.mediaservices.extensions
            //3. Create context
            var _context = new CloudMediaContext(AccountName, AccountKey);
            //4. Get asset
            var asset = (from a in _context.Assets
                         where a.Name == AssetName
                         select a).FirstOrDefault();
            //5. Get thumbnail configuration from a XML file
            var ThumbnailConfig = File.ReadAllText("Thumbnail_Configuration.xml");
            //6. Get the processor
            var processor = _context.MediaProcessors.GetLatestMediaProcessorByName(MediaProcessorNames.WindowsAzureMediaEncoder);
            //7. Create a job
            var job = _context.Jobs.Create("Thumbnail job");
            //8. Create a task
            ITask task = job.Tasks.AddNew("Thumbnail task",
                processor,
                //MediaEncoderTaskPresetStrings.Thumbnails,
                ThumbnailConfig,
                TaskOptions.None);
            //9. Add the input asset
            task.InputAssets.Add(asset);
            //10. Define the output asset name
            task.OutputAssets.AddNew(string.Format("{0} Thumbnails", AssetName), AssetCreationOptions.None);
            //11. Wait for the result
            job.Submit();
            var jobTask = job.GetExecutionProgressTask(CancellationToken.None);
            jobTask.Wait();
            //12. Get the primary jpge file
            var output = job.OutputMediaAssets[0];
            //13. Create an access policy
            var accessPolicy = _context.AccessPolicies.Create("Read Policy", TimeSpan.FromDays(10), AccessPermissions.Read);
            //14. Create a locator
            var locator = _context.Locators.CreateSasLocator(output, accessPolicy);
            //15. Select the primary file
            var primaryFile = (from a in output.AssetFiles
                               where a.IsPrimary == true
                               select a).FirstOrDefault();
            //16. Build a URL
            Console.WriteLine("Thumbnail locator:n{0}/{1}{2}n", locator.BaseUri, primaryFile.Name, locator.ContentAccessComponent);
            Console.ReadLine();
        }
    }
}
  1. We need the asset name and our account credentials.
  2. Install windowsazure.mediaservices via Nuget.
  3. In this example we use also Windows Azure Media Services SDK NET Extensions.
  4. Get the context to access our account.
  5. We retrieve the asset which we want to generate thumbnails.
  6. There are two ways to create thumbnails: using the default preset (MediaEncoderTaskPresetStrings.Thumbnails in the creation of the task) or using the following XML with custom values:
    <?xml version="1.0" encoding="utf-8"?>
    <Thumbnail Size="30%,*" Type="Jpeg" Filename="{OriginalFilename}_{ThumbnailIndex}.{DefaultExtension}">
      <Time Value="0:3:19"/>
    </Thumbnail>

    We use Size attribute to specify the width of the image and an asterisk to keep the aspect ratio. We can also choose the image format through the Type attribute and even use a pattern for the file name through Filename. Finally, we use Time in order to choose the point in the video where we want to take the picture, in this example I selected minute 3 and second 19. It’s also possible to generate more than one capture using Value, Step, Stop, if we wanted several samples. You can find more information about the configuration here.

  7. Get Windows Azure Media Encoder processor.
  8. Create the job.
  9. Define the task passing the processor, configuration XML and the type of task.
  10. Add the asset within InputAssets.
  11. We created an output asset that contains the result, in this case the thumbnail.
  12. Launch the job and wait for the result.
  13. Get the asset from job.OutputMediaAssets[0].
  14. Create a read-only access policy.
  15. Generate a Sas locator for the asset. If you want to know more about publishing you can check out the post Publish assets with Windows Azure SDK NET Media Services.
  16. If you have generated multiple thumbnails for a video, one of them must be the principal file. To select it we can use the isPrimary property.
  17. Finally, we build the URL to access the image.
  18.  

    If we launch the application, the result will be similar to the following:

    Console locator thumbnail

    Copy the resulting URL in the browser to verify that the model has been generated successfully:

    Frozen thumbnail

    Hope this helps!

    Happy weekend!