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

在本快速入门中,你将使用计算机视觉的 REST API 基于图像生成缩略图。In this quickstart, you generate a thumbnail from an image by using Computer Vision's REST API. 使用获取缩略图方法,可以生成图像的缩略图。With the Get Thumbnail method, you can 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.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial before you begin.

先决条件Prerequisites

创建和运行示例应用程序Create and run the sample application

要在 Visual Studio 中创建示例,请执行以下步骤:To create the sample in Visual Studio, do the following steps:

  1. 使用 Visual C# 控制台应用模板在 Visual Studio 中创建新的 Visual Studio 解决方案。Create a new Visual Studio solution in Visual Studio, using the Visual C# Console App template.
  2. 安装 Newtonsoft.Json NuGet 包。Install the Newtonsoft.Json NuGet package.
    1. 在菜单上,单击“工具”,然后依次选择“NuGet 包管理器”、“管理解决方案的 NuGet 包” 。On the menu, click Tools, select NuGet Package Manager, then Manage NuGet Packages for Solution.
    2. 单击“浏览”选项卡,在“搜索”框中键入“Newtonsoft.Json” 。Click the Browse tab, and in the Search box type "Newtonsoft.Json".
    3. 选择显示的 Newtonsoft.Json,单击项目名称旁边的复选框,然后单击“安装” 。Select Newtonsoft.Json when it displays, then click the checkbox next to your project name, and Install.
  3. Program.cs 中的代码替换为以下代码,然后根据需要在代码中进行以下更改:Replace the code in Program.cs with the following code, and then make the following changes in code where needed:
    1. subscriptionKey 的值替换为你的订阅密钥。Replace the value of subscriptionKey with your subscription key.
    2. 如有必要,请将 uriBase 的值替换为获取的订阅密钥所在的 Azure 区域中的获取缩略图方法的终结点 URL。Replace the value of uriBase with the endpoint URL for the Get Thumbnail method from the Azure region where you obtained your subscription keys, if necessary.
  4. 运行该程序。Run the program.
  5. 在提示符处,输入本地图像的路径。At the prompt, enter the path to a local image.
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace CSHttpClientSample
{
    static class Program
    {
        // Replace <Subscription Key> with your valid subscription key.
        const string subscriptionKey = "<Subscription Key>";

        const string uriBase =
            "https://api.cognitive.azure.cn/vision/v2.0/generateThumbnail";

        static void Main()
        {
            // Get the path and filename to process from the user.
            Console.WriteLine("Thumbnail:");
            Console.Write(
                "Enter the path to the image you wish to use to create a thumbnail image: ");
            string imageFilePath = Console.ReadLine();

            if (File.Exists(imageFilePath))
            {
                // Call the REST API method.
                Console.WriteLine("\nWait a moment for the results to appear.\n");
                MakeThumbNailRequest(imageFilePath).Wait();
            }
            else
            {
                Console.WriteLine("\nInvalid file path");
            }
            Console.WriteLine("\nPress Enter to exit...");
            Console.ReadLine();
        }

        /// <summary>
        /// Gets a thumbnail image from the specified image file by using
        /// the Computer Vision REST API.
        /// </summary>
        /// <param name="imageFilePath">The image file to use to create the thumbnail image.</param>
        static async Task MakeThumbNailRequest(string imageFilePath)
        {
            try
            {
                HttpClient client = new HttpClient();

                // Request headers.
                client.DefaultRequestHeaders.Add(
                    "Ocp-Apim-Subscription-Key", subscriptionKey);

                // Request parameters.
                // The width and height parameters specify a thumbnail that's 
                // 200 pixels wide and 150 pixels high.
                // The smartCropping parameter is set to true, to enable smart cropping.
                string requestParameters = "width=200&height=150&smartCropping=true";

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

                HttpResponseMessage response;

                // 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.
                    response = await client.PostAsync(uri, content);
                }

                // Check the HTTP status code of the response. If successful, display
                // display the response and save the thumbnail.
                if (response.IsSuccessStatusCode)
                {
                    // Display the response data.
                    Console.WriteLine("\nResponse:\n{0}", response);

                    // Get the image data for the thumbnail from the response.
                    byte[] thumbnailImageData =
                        await response.Content.ReadAsByteArrayAsync();

                    // Save the thumbnail to the same folder as the original image,
                    // using the original name with the suffix "_thumb".
                    // Note: This will overwrite an existing file of the same name.
                    string thumbnailFilePath =
                        imageFilePath.Insert(imageFilePath.Length - 4, "_thumb");
                    File.WriteAllBytes(thumbnailFilePath, thumbnailImageData);
                    Console.WriteLine("\nThumbnail written to: {0}", 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);
            }
        }

        /// <summary>
        /// Returns the contents of the specified file as a byte array.
        /// </summary>
        /// <param name="imageFilePath">The image file to read.</param>
        /// <returns>The byte array of the image data.</returns>
        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);
            }
        }
    }
}

检查响应Examine the response

成功的响应将以二进制数据形式返回,这些数据表示缩略图的图像数据。A successful response is returned as binary data, which represents the image data for the thumbnail. 如果请求成功,缩略图将保存到与本地图像相同的文件夹,使用原始名称并以“_thumb”作为后缀。If the request succeeds, the thumbnail is saved to the same folder as the local image, using the original name with the suffix "_thumb". 如果请求失败,则响应包含错误代码和消息,以帮助确定问题所在。If the request fails, the response contains an error code and a message to help determine what went wrong.

示例应用程序会在控制台窗口中显示成功的响应,如下例所示:The sample application displays a successful response in the console window, similar to the following example:

Response:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Pragma: no-cache
  apim-request-id: 131eb5b4-5807-466d-9656-4c1ef0a64c9b
  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  x-content-type-options: nosniff
  Cache-Control: no-cache
  Date: Tue, 06 Jun 2017 20:54:07 GMT
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Content-Length: 5800
  Content-Type: image/jpeg
  Expires: -1
}

后续步骤Next steps

浏览一款基本 Windows 应用程序,该应用程序使用计算机视觉执行光学字符识别 (OCR)、创建智能裁剪缩略图,并对图像中的视觉特征(包括人脸)进行检测、分类、标记和描述。Explore a basic Windows application that uses Computer Vision to perform optical character recognition (OCR); create smart-cropped thumbnails; plus detect, categorize, tag, and describe visual features, including faces, in an image. 要快速体验计算机视觉 API,请尝试使用 Open API 测试控制台To rapidly experiment with the Computer Vision APIs, try the Open API testing console.