Codifica Base64

Puoi fornire dati immagine all'API Cloud Vision specificando il percorso dell'URI l'immagine o inviando i dati immagine come testo con codifica Base64.

Utilizzo della riga di comando

All'interno di una richiesta gRPC, puoi semplicemente scrivere direttamente i dati binari; ma quando si effettua una richiesta REST viene usato JSON. JSON è un formato di testo che non supporta direttamente i dati binari, quindi dovrete convertire tali dati binari in testo utilizzando Codifica Base64.

La maggior parte degli ambienti di sviluppo contiene un'utilità base64 nativa Codificare un file binario in dati di testo ASCII. Per codificare un file:

Linux

Codifica il file utilizzando lo strumento a riga di comando base64, assicurandoti di evitare il ritorno a capo automatico usando il flag -w 0:

base64 INPUT_FILE -w 0 > OUTPUT_FILE

macOS

Codifica il file utilizzando lo strumento a riga di comando base64:

base64 -i INPUT_FILE -o OUTPUT_FILE

Windows

Codifica il file utilizzando lo strumento Base64.exe:

Base64.exe -e INPUT_FILE > OUTPUT_FILE

PowerShell

Codifica il file utilizzando il metodo Convert.ToBase64String:

[Convert]::ToBase64String([IO.File]::ReadAllBytes("./INPUT_FILE")) > OUTPUT_FILE

Crea un file di richiesta JSON che includa i dati con codifica 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=..."
        }
      }
    }
  ]
}

Utilizzo delle librerie client

Non incorporare dati binari nelle richieste tramite editor di testo desiderabile o pratico. In pratica, incorporerai file con codifica Base64 all'interno del codice client. Tutti i linguaggi di programmazione supportati hanno meccanismi integrati per contenuti con codifica 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.
byte[] imageData = Base64.encodeBase64(imageFile.getBytes());
String encodedString = Base64.getEncoder().encodeToString(imageData);

Vai

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)