שירותי 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, אפשר לקודד קובצי תמונה ב-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)