Vertex AI 服務

Base64 編碼

如要提供圖片資料進行光學字元辨識,請指定圖片的 URI 路徑,或以 base64 編碼文字的形式傳送圖片資料。

大多數開發環境都包含原生 base64 公用程式,可將二進位圖片編碼為 ASCII 文字資料。如要編碼圖片檔:

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)