Base64 エンコード

Vision API に画像データを提供するには、画像の URI パスを指定するか、画像データを Base64 エンコード テキストとして送信します。

コマンドラインの使用

gRPC リクエスト内に単純にバイナリデータを書き込むことができますが、REST リクエストを行う際には、JSON が使われます。JSON はバイナリデータを直接サポートしていないテキスト形式であるため、それらのバイナリデータは Base64 エンコードを使用して、テキストに変換する必要があります。

ほとんどの開発環境には、バイナリを ASCII テキストデータにエンコードするネイティブの base64 ユーティリティがあります。ファイルをエンコードするには:

Linux

base64 コマンドライン ツールを使用してファイルをエンコードし、-w 0 フラグを使用して、行の折り返しを防ぎます。

 base64 INPUT_FILE -w 0 > OUTPUT_FILE 

macOS

base64 コマンドライン ツールを使用してファイルをエンコードします。

 base64 -i INPUT_FILE -o OUTPUT_FILE 

Windows

Base64.exe ツールを使用してファイルをエンコードします。

 Base64.exe -e INPUT_FILE > OUTPUT_FILE 

PowerShell

Convert.ToBase64String メソッドを使用してファイルをエンコードします。

 [Convert]::ToBase64String([IO.File]::ReadAllBytes("./INPUT_FILE")) > OUTPUT_FILE 

base64 エンコードされたデータをインラインで挿入して、JSON リクエスト ファイルを作成します。

JSON

{   "requests": [     {       "image": {         "content": "BASE64_ENCODED_DATA"       },       "features": [         {           "type": "LABEL_DETECTION",           "maxResults": 1         }       ]     }   ] }

クライアント ライブラリの使用

テキスト エディタを使ってリクエストにバイナリデータを埋め込むことは実用性に欠け、また望ましくありません。実際には、クライアント コード内に base64 エンコード ファイルを埋め込みます。サポートされるすべてのプログラミング言語には、base64 エンコード コンテンツの組み込みメカニズムがあります。

Python

# Import the base64 encoding library. import base64  # Pass the image data to an encoding function. def encode_image(image):     with open(image, "rb") as image_file:         encoded_string = base64.b64encode(image_file.read())     return encoded_string 

Node.js

// Read the file into memory. var fs = require('fs'); var imageFile = fs.readFileSync('/path/to/file');  // Convert the image data to a Buffer and base64 encode it. var encoded = Buffer.from(imageFile).toString('base64'); 

Java

// Import the Base64 encoding library. import org.apache.commons.codec.binary.Base64;  // Encode the image. String encodedString = Base64.getEncoder().encodeToString(imageFile.getBytes()); 

Go

import (     "bufio"     "encoding/base64"     "io"     "os" )  // Open image file. f, _ := os.Open("image.jpg")  // Read entire image into byte slice. reader := bufio.NewReader(f) content, _ := io.ReadAll(reader)  // Encode image as base64. base64.StdEncoding.EncodeToString(content)