Search code examples
rubyazureazure-hub

What is the correct syntax to pass a base64 instead of a url to Microsoft Azure Computer vision API using Ruby


require 'net/http'

uri = URI('https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr')
uri.query = URI.encode_www_form({

    'language' => 'unk',
    'detectOrientation ' => 'true'
})

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

request['Content-Type'] = 'application/octet-stream'

request['Ocp-Apim-Subscription-Key'] = 'MY_SUBSCRIPTION_KEY'

request.body = "raw_image_binary"


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

puts response.body

I got this as a response.

{"code":"InvalidImageFormat","requestId":"3aee7147-2acc-4f64-b1c6-8453815eda38","message":"Input data is not a valid image."}

HELP!!


Solution

  • It sounds like you want to pass an image file to Azure Computer Vision API via application/octet-stream content type in Ruby, so you need to pass binary image data to response.body, not pass the base64 string of an image.

    Please use the code below instead of the current one to make it works.

    # Supported image formats: JPEG, PNG, GIF, BMP.
    request.body = File.binread("<your image file name>") 
    # Or `request.body = File.open("<your image file name>") {|io| io.read}` also works