Base64 인코딩

이미지 데이터를 Base64 인코딩 텍스트로 전송하여 AutoML Vision API에 제공할 수 있습니다.

명령줄 사용

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

{
  "payload": {
    "image": {
      "imageBytes": "/9j/4QAYRXhpZgAA...base64-encoded-image...9tAVx/zDQDlGxn//2Q=="
    }
  },
  "params": {
    string: string,
    ...
  }
}

클라이언트 라이브러리 사용

텍스트 편집기를 통해 바이너리 데이터를 요청에 삽입하는 것은 바람직하지 않으며 실용적이지도 않습니다. 실제로는 클라이언트 코드에 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');

자바

// Import the Base64 encoding library.
import org.apache.commons.codec.binary.Base64;

// Encode the image.
byte[] imageData = Base64.encodeBase64(imageFile.getBytes());
String encodedString = Base64.getEncoder().encodeToString(imageData);

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)