使用 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)
}