כדי לספק נתוני תמונה ל-Cloud Vision API, אפשר לציין את נתיב ה-URI לתמונה או לשלוח את נתוני התמונה כטקסט בקידוד base64.
שימוש בשורת הפקודה
בבקשת gRPC, אפשר פשוט לכתוב נתונים בינאריים ישירות, אבל כששולחים בקשת REST משתמשים ב-JSON. JSON הוא פורמט טקסט שלא תומך ישירות בנתונים בינאריים, ולכן צריך להמיר את הנתונים הבינאריים האלה לטקסט באמצעות קידוד Base64.
רוב סביבות הפיתוח מכילות כלי base64 מובנה לקידוד קובץ בינארי לנתוני טקסט ב-ASCII. כדי לקודד קובץ:
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
יוצרים קובץ בקשה בפורמט JSON, ומוסיפים את הנתונים בקידוד base64:
JSON
{ "requests": [ { "image": { "content": "BASE64_ENCODED_DATA" }, "features": [ { "type": "PRODUCT_SEARCH" } ], "imageContext": { "productSearchParams": { "productSet": "projects/PROJECT_ID/locations/LOCATION/productSets/PRODUCT_SET_ID", "productCategories": [ "apparel" ], "filter": "style=... AND color=..." } } } ] }
שימוש בספריות לקוח
הטמעה של נתונים בינאריים בבקשות באמצעות כלים לעריכת טקסט היא לא רצויה ולא מעשית. בפועל, תטמיעו קבצים בקידוד 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');
Java
// Import the Base64 encoding library.
import org.apache.commons.codec.binary.Base64;
// Encode the image.
String encodedString = Base64.getEncoder().encodeToString(imageFile.getBytes());
המשך
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)