对文件进行 Base64 编码和解码

对图片进行 Base64 编码

如需发出生成图片请求,您必须以 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

{   "instances": [     {       "prompt": "TEXT_PROMPT",       "image": {         "bytes_base64_encoded": "B64_BASE_IMAGE"       }     }   ] }

使用客户端库

通过文本编辑器将二进制数据嵌入请求中既不可取也不实用。在实际使用中,您应在客户端代码中嵌入使用 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()); 

Go

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) 

对图片进行 Base64 解码

API 请求以 base64 编码字符串的形式返回生成或修改的图片。您可以使用以下客户端库示例解码这些数据并将其本地保存为图片文件。

Python

# Import the base64 encoding library. import base64  # Pass the base64 encoded image data to a decoding function and save image file. def decode_image(b64_encoded_string):    with open("b64DecodedImage.png", "wb") as fh:      fh.write(base64.decodebytes(b64_encoded_string)) 

Node.js

var fs = require('fs');  // Create buffer object, specifying base64 as encoding var buf = Buffer.from(base64str,'base64');  // Write buffer content to a file fs.writeFile("b64DecodedImage.png", buf, function(error){   if(error){     throw error;   }else{     console.log('File created from base64 string');     return true;   } }); 

Java

// Import libraries import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils;  // Create new file File file = new File("./b64DecodedImage.png"); // Convert base64 encoded string to byte array byte[] bytes = Base64.decodeBase64("base64"); // Write out file FileUtils.writeByteArrayToFile(file, bytes); 

Go

// Import packages import (    "encoding/base64"    "io"    "os" )  // Add encoded file string var b64 = `TWFuIGlz...Vhc3VyZS4=`  // Decode base64-encoded string dec, err := base64.StdEncoding.DecodeString(b64) if err != nil {     panic(err) }  // Create output file f, err := os.Create("b64DecodedImage.png") if err != nil {     panic(err) } defer f.Close()  if _, err := f.Write(dec); err != nil {     panic(err) } if err := f.Sync(); err != nil {     panic(err) }