Base64 エンコード
光学文字認識用の画像データを提供するには、画像の URI パスを指定するか、画像データを Base64 エンコード テキストとして送信します。
ほとんどの開発環境には、バイナリ画像を ASCII テキストデータにエンコードするネイティブの base64 ユーティリティがあります。画像ファイルをエンコードする方法は次のとおりです。
Linux
base64 input.jpg > output.txt
Mac OSX
base64 -i input.jpg -o output.txt
Windows
C:> Base64.exe -e input.jpg > output.txt
PowerShell
[Convert]::ToBase64String([IO.File]::ReadAllBytes("./input.jpg")) > output.txt
この出力画像データは JSON リクエスト内で次のようにネイティブに使用できます。
{
"requests":[
{
"image":{
"content": "BASE64_ENCODED_DATA"
},
"features": [
{
"type":"TEXT_DETECTION",
"maxResults":1
}
]
}
]
}
プログラミング言語ごとに、画像ファイルを base64 エンコードする方法は異なります。
Python
Python で画像ファイルを base64 エンコードする方法は次のとおりです。
# Import the base64 encoding library.
import base64
# Pass the image data to an encoding function.
def encode_image(image):
image_content = image.read()
return base64.b64encode(image_content)
Node.js
Node.js で画像ファイルを base64 エンコードする方法は次のとおりです。
// 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
Java で画像ファイルを base64 エンコードする方法は次のとおりです。
// Import the Base64 encoding library.
import org.apache.commons.codec.binary.Base64;
// Encode the image.
byte[] imageData = Base64.encodeBase64(imageFile.getBytes());
Go
Go で画像ファイルを base64 エンコードする方法は次のとおりです。
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)