Bing Image Search API - 按图像大小过滤V5(使用Ruby)

时间:2017-05-31 16:26:55

标签: ruby image api search bing

我想限制搜索图片使用  “过滤查询参数(https://msdn.microsoft.com/en-us/library/dn760791.aspx)”。但我总是得到大小在250到300像素(宽度和高度)的照片,虽然我想要它们,大于500 x 500像素。 我知道已有类似的问题(Bing Image Search API filter by image size),但我无法解决问题。

我正在使用Ruby并且代码正在关注。 有什么问题?

require "open-uri"
require "FileUtils"
require 'net/http'
require 'json'


@dirName = "/Users/hoge/img"
FileUtils.mkdir_p(@dirName) unless FileTest.exist?(@dirName)

def save_image(url, num)
  filePath = "#{@dirName}/christ#{num.to_s}.jpg"
  open(filePath, 'wb') do |output|
    open(url) do |data|
      output.write(data.read)
    end
  end
end

search_word = 'christ painting'
count = 5
size = 'Large'


uri = URI('https://api.cognitive.microsoft.com/bing/v5.0/images/search')
uri.query = URI.encode_www_form({
    'q' => search_word,
    'count' => count,

    'size' => size
})
request = Net::HTTP::Post.new(uri.request_uri)
request['Content-Type'] = 'multipart/form-data'
request['Ocp-Apim-Subscription-Key'] = 'mykey' # Fix Me
request.body = "{body}"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
  http.request(request)
end

count.times do |i|
  begin
    image_url = JSON.parse(response.body)["value"][i]["thumbnailUrl"]
    save_image(image_url, i)
  rescue => e
    puts "image#{i} is error!"
    puts e
  end
end

0 个答案:

没有答案