快速入门:使用计算机视觉 SDK 和 C# 生成缩略图Quickstart: Generate a thumbnail using the Computer Vision SDK and C#

在本快速入门中,你将使用适用于 C# 的计算机视觉 SDK 基于图像生成智能裁剪的缩略图。In this quickstart, you will generate a smart-cropped thumbnail from an image using the Computer Vision SDK for C#. 如果你愿意,可以从 GitHub 上的认知服务 Csharp 视觉存储库下载本指南中的代码作为完整的示例应用。If you wish, you can download the code in this guide as a complete sample app from the Cognitive Services Csharp Vision repo on GitHub.

先决条件Prerequisites

GenerateThumbnailAsync 方法GenerateThumbnailAsync method

可以使用这些方法生成图像的缩略图。You can use these methods to generate a thumbnail of an image. 可以指定高度和宽度,可以与输入图像的纵横比不同。You specify the height and width, which can differ from the aspect ratio of the input image. 计算机视觉使用智能裁剪来智能识别感兴趣的区域并基于该区域生成裁剪坐标。Computer Vision uses smart cropping to intelligently identify the area of interest and generate cropping coordinates based on that region.

若要运行此示例,请执行以下步骤:To run the sample, do the following steps:

  1. 在 Visual Studio 中创建一个新的 Visual C# 控制台应用。Create a new Visual C# Console App in Visual Studio.

  2. 安装计算机视觉客户端库 NuGet 包。Install the Computer Vision client library NuGet package.

    1. 在菜单上,单击“工具”,然后依次选择“NuGet 包管理器”、“管理解决方案的 NuGet 包”。On the menu, click Tools, select NuGet Package Manager, then Manage NuGet Packages for Solution.
    2. 单击“浏览”选项卡,在“搜索”框中键入“Microsoft.Azure.CognitiveServices.Vision.ComputerVision”。Click the Browse tab, and in the Search box type "Microsoft.Azure.CognitiveServices.Vision.ComputerVision".
    3. 选择显示的 Microsoft.Azure.CognitiveServices.Vision.ComputerVision,单击项目名称旁边的复选框,然后单击“安装”。Select Microsoft.Azure.CognitiveServices.Vision.ComputerVision when it displays, then click the checkbox next to your project name, and Install.
  3. Program.cs 替换为以下代码。Replace Program.cs with the following code. GenerateThumbnailAsyncGenerateThumbnailInStreamAsync 方法分别为远程图像和本地图像包装获取缩略图 APIThe GenerateThumbnailAsync and GenerateThumbnailInStreamAsync methods wrap the Get Thumbnail API for remote and local images, respectively.

    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
    
    using System;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace ImageThumbnail
    {
        class Program
        {
            private const bool writeThumbnailToDisk = false;
    
            // subscriptionKey = "0123456789abcdef0123456789ABCDEF"
            private const string subscriptionKey = "<SubscriptionKey>";
    
            // localImagePath = @"C:\Documents\LocalImage.jpg"
            private const string localImagePath = @"<LocalImage>";
    
            private const string remoteImageUrl =
                "https://upload.wikimedia.org/wikipedia/commons/9/94/Bloodhound_Puppy.jpg";
    
            private const int thumbnailWidth = 100;
            private const int thumbnailHeight = 100;
    
            static void Main(string[] args)
            {
                ComputerVisionClient computerVision = new ComputerVisionClient(
                    new ApiKeyServiceClientCredentials(subscriptionKey),
                    new System.Net.Http.DelegatingHandler[] { });
    
                computerVision.Endpoint = "https://api.cognitive.azure.cn";
    
                Console.WriteLine("Images being analyzed ...\n");
                var t1 = GetRemoteThumbnailAsync(computerVision, remoteImageUrl);
                var t2 = GetLocalThumbnailAsnc(computerVision, localImagePath);
    
                Task.WhenAll(t1, t2).Wait(5000);
                Console.WriteLine("Press ENTER to exit");
                Console.ReadLine();
            }
    
            // Create a thumbnail from a remote image
            private static async Task GetRemoteThumbnailAsync(
                ComputerVisionClient computerVision, string imageUrl)
            {
                if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
                {
                    Console.WriteLine(
                        "\nInvalid remoteImageUrl:\n{0} \n", imageUrl);
                    return;
                }
    
                Stream thumbnail = await computerVision.GenerateThumbnailAsync(
                    thumbnailWidth, thumbnailHeight, imageUrl, true);
    
                string path = Environment.CurrentDirectory;
                string imageName = imageUrl.Substring(imageUrl.LastIndexOf('/') + 1);
                string thumbnailFilePath =
                    path + "\\" + imageName.Insert(imageName.Length - 4, "_thumb");
    
                // Save the thumbnail to the current working directory,
                // using the original name with the suffix "_thumb".
                SaveThumbnail(thumbnail, thumbnailFilePath);
            }
    
            // Create a thumbnail from a local image
            private static async Task GetLocalThumbnailAsnc(
                ComputerVisionClient computerVision, string imagePath)
            {
                if (!File.Exists(imagePath))
                {
                    Console.WriteLine(
                        "\nUnable to open or read localImagePath:\n{0} \n", imagePath);
                    return;
                }
    
                using (Stream imageStream = File.OpenRead(imagePath))
                {
                    Stream thumbnail = await computerVision.GenerateThumbnailInStreamAsync(
                        thumbnailWidth, thumbnailHeight, imageStream, true);
    
                    string thumbnailFilePath =
                        localImagePath.Insert(localImagePath.Length - 4, "_thumb");
    
                    // Save the thumbnail to the same folder as the original image,
                    // using the original name with the suffix "_thumb".
                    SaveThumbnail(thumbnail, thumbnailFilePath);
                }
            }
    
            // Save the thumbnail locally.
            // NOTE: This will overwrite an existing file of the same name.
            private static void SaveThumbnail(Stream thumbnail, string thumbnailFilePath)
            {
                if (writeThumbnailToDisk)
                {
                    using (Stream file = File.Create(thumbnailFilePath))
                    {
                        thumbnail.CopyTo(file);
                    }
                }
                Console.WriteLine("Thumbnail {0} written to: {1}\n",
                    writeThumbnailToDisk ? "" : "NOT", thumbnailFilePath);
            }
        }
    }
    
  4. <Subscription Key> 替换为有效订阅密钥。Replace <Subscription Key> with your valid subscription key.

  5. 如有必要,将 computerVision.Endpoint 更改为与订阅密钥关联的 Azure 区域。Change computerVision.Endpoint to the Azure region associated with your subscription keys, if necessary.

  6. (可选)将 <LocalImage> 替换为某个本地图像的路径和文件名(如果未设置将忽略)。Optionally, replace <LocalImage> with the path and file name of a local image (will be ignored if not set).

  7. (可选)将 remoteImageUrl 设置为另一图像。Optionally, set remoteImageUrl to a different image.

  8. (可选)将 writeThumbnailToDisk 设置为 true 以将缩略图保存到磁盘。Optionally, set writeThumbnailToDisk to true to save the thumbnail to disk.

  9. 运行该程序。Run the program.

检查响应Examine the response

成功的响应将在本地保存每个图像的缩略图,并显示缩略图的位置,例如:A successful response saves the thumbnail for each image locally and displays the thumbnail's location, for example:

Thumbnail written to: C:\Documents\LocalImage_thumb.jpg

Thumbnail written to: ...\bin\Debug\Bloodhound_Puppy_thumb.jpg

后续步骤Next steps

探索用于分析图像、检测名人和地标、创建缩略图以及提取印刷体文本和手写文本的计算机视觉 API。Explore the Computer Vision APIs used to analyze an image, detect celebrities and landmarks, create a thumbnail, and extract printed and handwritten text.