Quickstart: Generate a thumbnail using the Computer Vision REST API and Ruby

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.

If you don't have an Azure subscription, create a Trial before you begin.

Prerequisites

  • You must have Ruby 2.4.x or later 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. Replace <Subscription Key> with your subscription key.
    2. Replace https://api.cognitive.azure.cn/vision/v2.0/analyze with the endpoint URL for the Get Thumbnail method in the Azure region where you obtained your subscription keys, if necessary.
    3. Optionally, replace https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Shorkie_Poo_Puppy.jpg/1280px-Shorkie_Poo_Puppy.jpg\ with the URL of a different image for which you want to generate a thumbnail.
  3. Save the code as a file with an .rb extension. For example, get-thumbnail.rb.
  4. Open a command prompt window.
  5. At the prompt, use the ruby command to run the sample. For example, ruby get-thumbnail.rb.
require 'net/http'

uri = URI('https://api.cognitive.azure.cn/vision/v2.0/generateThumbnail')
uri.query = URI.encode_www_form({
    # Request parameters
    'width' => '100',
    'height' => '100',
    'smartCropping' => 'true'
})

request = Net::HTTP::Post.new(uri.request_uri)

# Request headers
# Replace <Subscription Key> with your valid subscription key.
request['Ocp-Apim-Subscription-Key'] = '<Subscription Key>'
request['Content-Type'] = 'application/json'

request.body =
    "{\"url\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/" +
    "Shorkie_Poo_Puppy.jpg/1280px-Shorkie_Poo_Puppy.jpg\"}"

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

#puts response.body

Examine the response

A successful response is returned as binary data, which represents the image data for the thumbnail. 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

Explore the Computer Vision API used to analyze an image, detect celebrities and landmarks, create a thumbnail, and extract printed and handwritten text. To rapidly experiment with the Computer Vision API, try the Open API testing console.