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

在本快速入门中,你将使用计算机视觉 REST API 基于图像生成缩略图。In this quickstart, you will generate a thumbnail from an image using the Computer Vision REST API. 可以指定高度和宽度,可以与输入图像的纵横比不同。You specify the height and width, which can differ in aspect ratio from the input image. 计算机视觉使用智能裁剪来智能识别感兴趣的区域并基于该区域生成裁剪坐标。Computer Vision uses smart cropping to intelligently identify the area of interest and generate cropping coordinates based on that region.

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅An Azure subscription - Create one for trial
  • 拥有 Azure 订阅后,在 Azure 门户中创建计算机视觉资源 ,获取密钥和终结点。Once you have your Azure subscription, create a Computer Vision resource in the Azure portal to get your key and endpoint. 部署后,单击“转到资源”。After it deploys, click Go to resource.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到计算机视觉服务。You will need the key and endpoint from the resource you create to connect your application to the Computer Vision service. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart.
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.

创建并运行示例Create and run the sample

要创建和运行示例,请执行以下步骤:To create and run the sample, do the following steps:

  1. 创建一个名为 get-thumbnail.html 的文件,在文本编辑器中打开它,然后将以下代码复制到其中。Create a file called get-thumbnail.html, open it in a text editor, and copy the following code into it.
  2. (可选)将 inputImage 控件的 value 属性的值替换为要分析的其他图像的 URL。Optionally, replace the value of the value attribute of the inputImage control with the URL of a different image that you want to analyze.
  3. 打开一个浏览器窗口。Open a browser window.
  4. 在浏览器中,将文件拖放到浏览器窗口。In the browser, drag and drop the file into the browser window.
  5. 当网页显示在浏览器中时,请将订阅密钥和终结点 URL 粘贴到相应的输入框中。When the webpage is displayed in the browser, paste your subscription key and endpoint URL into the appropriate input boxes.
  6. 最后,选择“生成缩略图”按钮。Finally, select the Generate thumbnail button.
<!DOCTYPE html>
<html>
<head>
    <title>Thumbnail Sample</title>
</head>
<body>

<script type="text/javascript">
    function processImage() {
        // **********************************************
        // *** Update or verify the following values. ***
        // **********************************************

        var subscriptionKey = document.getElementById("subscriptionKey").value;
        var endpoint = document.getElementById("endpointUrl").value;
        
        var uriBase = endpoint + "vision/v3.0/generateThumbnail";

        // Request parameters.
        var params = "?width=100&height=150&smartCropping=true";

        // Display the source image.
        var sourceImageUrl = document.getElementById("inputImage").value;
        document.querySelector("#sourceImage").src = sourceImageUrl;

        // Prepare the REST API call:

        // Create the HTTP Request object.
        var xhr = new XMLHttpRequest();

        // Identify the request as a POST, with the URL and parameters.
        xhr.open("POST", uriBase + params);

        // Add the request headers.
        xhr.setRequestHeader("Content-Type","application/json");
        xhr.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);

        // Set the response type to "blob" for the thumbnail image data.
        xhr.responseType = "blob";

        // Process the result of the REST API call.
        xhr.onreadystatechange = function(e) {
            if(xhr.readyState === XMLHttpRequest.DONE) {

                // Thumbnail successfully created.
                if (xhr.status === 200) {
                    // Show response headers.
                    var s = JSON.stringify(xhr.getAllResponseHeaders(), null, 2);
                    document.getElementById("responseTextArea").value =
                        JSON.stringify(xhr.getAllResponseHeaders(), null, 2);

                    // Show thumbnail image.
                    var urlCreator = window.URL || window.webkitURL;
                    var imageUrl = urlCreator.createObjectURL(this.response);
                    document.querySelector("#thumbnailImage").src = imageUrl;
                } else {
                    // Display the error message. The error message is the response
                    // body as a JSON string. The code in this code block extracts
                    // the JSON string from the blob response.
                    var reader = new FileReader();

                    // This event fires after the blob has been read.
                    reader.addEventListener('loadend', (e) => {
                        document.getElementById("responseTextArea").value =
                            JSON.stringify(JSON.parse(e.srcElement.result), null, 2);
                    });

                    // Start reading the blob as text.
                    reader.readAsText(xhr.response);
                }
            }
        }

        // Make the REST API call.
        xhr.send('{"url": ' + '"' + sourceImageUrl + '"}');
    };
</script>

<h1>Generate thumbnail image:</h1>
Enter the URL to an image to use in creating a thumbnail image,
then click the <strong>Generate thumbnail</strong> button.
<br><br>
Subscription key: 
<input type="text" name="subscriptionKey" id="subscriptionKey"
    value="" /> 
Endpoint URL:
<input type="text" name="endpointUrl" id="endpointUrl"
    value="" />
<br><br>
Image for thumbnail:
<input type="text" name="inputImage" id="inputImage"
    value="https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Shorkie_Poo_Puppy.jpg/1280px-Shorkie_Poo_Puppy.jpg" />
<button onclick="processImage()">Generate thumbnail</button>
<br><br>
<div id="wrapper" style="width:1160px; display:table;">
    <div id="jsonOutput" style="width:600px; display:table-cell;">
        Response:
        <br><br>
        <textarea id="responseTextArea" class="UIInput"
                  style="width:580px; height:400px;"></textarea>
    </div>
    <div id="imageDiv" style="width:420px; display:table-cell;">
        Source image:
        <br><br>
        <img id="sourceImage" width="400" />
    </div>
    <div id="thumbnailDiv" style="width:140px; display:table-cell;">
        Thumbnail:
        <br><br>
        <img id="thumbnailImage" />
    </div>
</div>
</body>
</html>

检查响应Examine the response

成功的响应将以二进制数据形式返回,这些数据表示缩略图的图像数据。A successful response is returned as binary data, which represents the image data for the thumbnail. 如果请求成功,会根据响应中的二进制数据生成缩略图,并在浏览器窗口中显示该缩略图。If the request succeeds, the thumbnail is generated from the binary data in the response and displayed in the browser window. 如果请求失败,则响应将显示在控制台窗口中。If the request fails, the response is displayed in the console window. 失败请求的响应包含错误代码和消息,用以帮助确定出错的地方。The response for the failed request contains an error code and a message to help determine what went wrong.

后续步骤Next steps

浏览一款 JavaScript 应用程序,该应用程序使用计算机视觉执行光学字符识别 (OCR)、创建智能裁剪缩略图,并对图像中的视觉特征(包括人脸)进行检测、分类、标记和描述。Explore a JavaScript 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 API, try the Open API testing console.