Base64 编码

将视频传递给 Video Intelligence API 时,您可以传递 Cloud Storage URI,也可以将视频数据直接嵌入请求的 content 字段中(该字段必须采用 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 工具对文件进行编码:

certutil -encodehex SOURCE_VIDEO_FILE > DEST_TEXT_FILE 0x40000001

PowerShell

使用 Convert.ToBase64String 方法对文件进行编码:

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

创建 JSON 请求文件,并内嵌 base64 编码的数据:

JSON

{
  "requests":[
    {
      "image":{
        "content": "ZkxhQwAAACIQABAAAAUJABtAA+gA8AB+W8FZndQvQAyjv..."
      },
      "features": [
        {
          "type":"LABEL_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
}

使用客户端库

通过文本编辑器将二进制数据嵌入请求中既不可取也不实用。在实际使用中,您应在客户端代码中嵌入使用 base64 编码的文件。所有受支持的编程语言都内置有适用于 base64 编码内容的机制。

Python

在 Python 中,base64 以如下示例代码对视频文件进行编码:

# Import the base64 encoding library.
import base64

# Pass the video data to an encoding function.
def encode_video(video):
  video_content = video.read()
  return base64.b64encode(video_content)

Node.js

在 Node.js 中,base64 以如下示例代码对视频文件进行编码:

// Read the file into memory.
var fs = require('fs');
var videoFile = fs.readFileSync('/path/to/file');

// Convert the video data to a Buffer and base64 encode it.
var encoded = new Buffer(videoFile).toString('base64');

Java

在 Java 中,您可以按如下所示对图片文件进行 Base64 编码:

// Import the Base64 encoding library.
import org.apache.commons.codec.binary.Base64;

// Encode the video.
byte[] videoData = Base64.encodeBase64(videoFile.getBytes());