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

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

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

先决条件Prerequisites

  • 必须安装有 GoYou must have Go installed.
  • 必须具有计算机视觉的订阅密钥。You must have a subscription key for Computer Vision. 你可以按照创建认知服务帐户中的说明订阅计算机视觉并获取密钥。You can follow the instructions in Create a Cognitive Services account to subscribe to Computer Vision and get your key.

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

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

  1. 将以下代码复制到文本编辑器中。Copy the following code into a text editor.
  2. 必要时在代码中进行如下更改: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.
    3. (可选)将 imageUrl 的值替换为生成缩略图时所依据的另一图像的 URL。Optionally, replace the value of imageUrl with the URL of a different image from which you want to generate a thumbnail.
  3. 将代码保存为以 .go 为扩展名的文件。Save the code as a file with a .go extension. 例如,get-thumbnail.goFor example, get-thumbnail.go.
  4. 打开命令提示符窗口。Open a command prompt window.
  5. 在提示符处运行 go build 命令,对文件中的包进行编译。At the prompt, run the go build command to compile the package from the file. 例如,go build get-thumbnail.goFor example, go build get-thumbnail.go.
  6. 在提示符处,运行所编译的包。At the prompt, run the compiled package. 例如,get-thumbnailFor example, get-thumbnail.
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

func main() {
    // Replace <Subscription Key> with your valid subscription key.
    const subscriptionKey = "<Subscription Key>"

    const uriBase =
        "https://api.cognitive.azure.cn/vision/v2.0/generateThumbnail"
    const imageUrl =
        "https://upload.wikimedia.org/wikipedia/commons/9/94/Bloodhound_Puppy.jpg"

    const params = "?width=100&height=100&smartCropping=true"
    const uri = uriBase + params
    const imageUrlEnc = "{\"url\":\"" + imageUrl + "\"}"

    reader := strings.NewReader(imageUrlEnc)

    // Create the HTTP client
    client := &http.Client{
        Timeout: time.Second * 2,
    }

    // Create the POST request, passing the image URL in the request body
    req, err := http.NewRequest("POST", uri, reader)
    if err != nil {
        panic(err)
    }

    // Add headers
    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)

    // Send the request and retrieve the response
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()

    // Read the response body.
    // Note, data is a byte array
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    // Parse the JSON data
    var f interface{}
    json.Unmarshal(data, &f)

    // Format and display the JSON result
    jsonFormatted, _ := json.MarshalIndent(f, "", "  ")
    fmt.Println(string(jsonFormatted))
}

检查响应Examine the response

成功的响应包含缩略图二进制数据。A successful response contains the thumbnail image binary data. 如果请求失败,则响应包含错误代码和消息,以帮助确定问题所在。If the request fails, the response contains an error code and a message to help determine what went wrong.

后续步骤Next steps

了解计算机视觉 API,它用于分析图像、检测名人和地标、创建缩略图,并提取印刷体文本和手写文本。Explore the Computer Vision API to analyze an image, detect celebrities and landmarks, create a thumbnail, and extract printed and handwritten text. 要快速体验计算机视觉 API,请尝试使用 Open API 测试控制台To rapidly experiment with the Computer Vision API, try the Open API testing console.