0

如何正確上傳適用於Google圖片的S3網址圖片?

我試圖圖像(保存在AWS S3 URL)發送給谷歌願景每第二個選項Base64編碼的documentation如下:發送到谷歌雲願景API如何上傳Google Vision API網址上的圖片 - Ruby

圖片可以通過兩種方式提供:

  1. 使用表單GS的谷歌雲存儲的URI:// bucketname /路徑/到/ IMAGE_FILENAME

  2. 作爲在JSON請求內發送的圖像數據。由於圖像數據必須以ASCII文本形式提供,因此所有圖像數據都應使用base64編碼進行轉義。

我使用Google-Cloud-Vision Gem

我試圖this previous answer about Base64 encoding,具有小的修改:

require 'google/cloud/vision' 
require 'base64' 
require 'googleauth' 
require 'open-uri' 

encoded_image = Base64.strict_encode64(open(image_url, &:read)) 

@vision = Google::Cloud::Vision.new 
image = @vision.image(encoded_image) 
annotation = @vision.annotate(image, labels: true, text: true) 

我已經在其他URL試圖在AWS網址圖像和圖像。

每次我從谷歌雲視通寶石得到這個錯誤: ArgumentError: Unable to convert (my_base_64_encoded_image) to an image

更新 - 成功地編碼和紅寶石解碼圖像只有

我已確認,此代碼:encoded_image = Base64.strict_encode64(open(image_url, &:read))作品通過以下方式:

# Using a random image from the interwebs 
image_url = "https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png" 
encoded_image = Base64.strict_encode64(open(image_url, &:read)) 

### now try to decode the encoded_image 
File.open("my-new-image.jpg", "wb") do |file| 
    file.write(Base64.strict_decode64(encoded_image)) 
end 
### great success 

那麼谷歌的這個問題是什麼?我編碼正確。

回答

1

如果您要使用谷歌雲視通的寶石,你需要按照創業板的文檔(使用非編碼的圖像),也許他做它的引擎蓋下。基於的文檔上

寶石google-cloud-vision,你可以像下面的代碼轉換你的圖像

open image_url do |img| 
    @vision = Google::Cloud::Vision.new 

    image = @vision.image(img) 
    # you can also use the class method from_io 
    # image = Google::Cloud::Vision::Image.from_io(img, @vision) 

    annotation = @vision.annotate(image, labels: true, text: true) 
end 
+1

Aaah,所以不要轉換爲Base64。只需使用一個tmpfile ...很好! – BigRon