이미지에 대한 URI 경로를 지정하거나 이미지 데이터를 base64로 인코딩된 텍스트로 전송하여 Vision API에 이미지 데이터를 제공할 수 있습니다.
대부분의 개발 환경에는 바이너리 이미지를 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":"LABEL_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');
자바
자바에서 이미지 파일을 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/ioutil" "os" ) // Open image file. f, _ := os.Open("image.jpg") // Read entire image into byte slice. reader := bufio.NewReader(f) content, _ := ioutil.ReadAll(reader) // Encode image as base64. base64.StdEncoding.EncodeToString(content)