您可以通过指定图片的 URI 路径或以 base64 编码文本形式发送图片数据,为 Vision API 提供图片数据。
大多数开发环境都包含一个原生“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":"LABEL_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/ioutil" "os" ) // Open image file. f, _ := os.Open("image.jpg") // Read entire image into byte slice. reader := bufio.NewReader(f) content, _ := ioutil.ReadAll(reader) // Encode image as base64. base64.StdEncoding.EncodeToString(content)