You can provide image data for prediction to the Vertex AI API by sending the image data as base64-encoded text.
Using the command line
Most development environments contain a native "base64" utility to encode a binary image into ASCII text data. To encode an image file:
Linux
base64 INPUT.EXT > OUTPUT.TXT
Mac OSX
base64 -i INPUT.EXT -o OUTPUT.TXT
Windows
C:> Base64.exe /e INPUT.EXT > OUTPUT.TXT
PowerShell
[Convert]::ToBase64String([IO.File]::ReadAllBytes("INPUT.EXT")) > OUTPUT.TXT
You can then use this output image data natively within the JSON request body:
{ "instances": [{ "content": "BASE64_ENCODED_DATA" }], "parameters": { "confidenceThreshold": DECIMAL, "maxPredictions": INTEGER } }
Using client libraries
Each programming language has its own way of base64 encoding image files. Depending on the operation this step may be included in the code sample:
Java
In Java, you can base64-encode image files as follows:
// 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);
Node.js
In Node.js, you can base64-encode image files as follows:
// 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');
Python
In Python, you can base64-encode image files as follows:
# 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