在現代的 Web 和行動應用程式中,為動畫 GIF 添加動態字幕、字幕或促銷訊息是一項常見需求。
GroupDocs.Watermark Cloud SDK for Java 提供了一個強大的基於 REST 的函式庫,使此任務變得簡單直接。
在本指南中,您將學習如何 使用 Java 中的 REST 為 GIF 添加文字覆蓋,查看完整的 Java 實作範例,探索等效的 cURL 命令,並了解所需的設定步驟。

在 Java 中使用 REST 添加文字覆蓋到 GIF - 示例代碼

此範例示範如何設定文字浮水印並將其套用至 GIF 檔案的每一幀。

import com.groupdocs.watermark.cloud.api.WatermarkApi;
import com.groupdocs.watermark.cloud.client.ApiException;
import com.groupdocs.watermark.cloud.client.Configuration;
import com.groupdocs.watermark.cloud.model.AddWatermarkRequest;
import com.groupdocs.watermark.cloud.model.AddWatermarkResponse;
import com.groupdocs.watermark.cloud.model.FileInfo;
import com.groupdocs.watermark.cloud.model.OutputFileInfo;
import com.groupdocs.watermark.cloud.model.TextWatermarkOptions;
import com.groupdocs.watermark.cloud.model.HorizontalAlignment;
import com.groupdocs.watermark.cloud.model.VerticalAlignment;

public class AddTextOverlayToGif {
    public static void main(String[] args) {
        // Initialize API configuration (replace with your actual clientId and clientSecret)
        Configuration config = new Configuration("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");
        WatermarkApi watermarkApi = new WatermarkApi(config);

// Prepare input file information
        FileInfo inputFile = new FileInfo();
        inputFile.setFilePath("input.gif");          // Path to the source GIF in the storage
        inputFile.setStorageName("MyStorage");       // Optional: name of the storage

// Prepare output file information
        OutputFileInfo outputFile = new OutputFileInfo();
        outputFile.setFilePath("output.gif");        // Desired path for the watermarked GIF
        outputFile.setStorageName("MyStorage");      // Optional: name of the storage

// Configure text watermark options
        TextWatermarkOptions textOptions = new TextWatermarkOptions();
        textOptions.setText("Sample Watermark");
        textOptions.setFontFamily("Arial");
        textOptions.setFontSize(24.0);
        textOptions.setColor("#FF0000");             // Red color in HEX
        textOptions.setOpacity(0.5);                 // 50% opacity
        textOptions.setRotationAngle(0.0);
        textOptions.setHorizontalAlignment(HorizontalAlignment.CENTER);
        textOptions.setVerticalAlignment(VerticalAlignment.MIDDLE);
        textOptions.setPageRange("1-");               // Apply to all frames/pages

// Build the request
        AddWatermarkRequest request = new AddWatermarkRequest();
        request.setFileInfo(inputFile);
        request.setOutputFileInfo(outputFile);
        request.setOptions(textOptions);

try {
            // Execute the request
            AddWatermarkResponse response = watermarkApi.addWatermark(request);
            System.out.println("Watermark added successfully. Output file: " + response.getPath());
        } catch (ApiException e) {
            System.err.println("Error while adding watermark: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

注意: 此程式碼範例展示了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參閱官方文件或聯繫支援團隊尋求協助。

使用 cURL 的 REST API 在 GIF 上疊加文字

以下是從終端執行的 cURL 命令,執行相同的操作。它們說明了完整的 REST 工作流程:身份驗證、上傳、添加水印和下載。

# 1. Obtain an access token
curl -X POST "https://api.groupdocs.cloud/v2.0/auth/token" \
     -H "Content-Type: application/json" \
     -d '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET"}'

在以下呼叫中將 YOUR_ACCESS_TOKEN 替換為上面返回的令牌。

# 2. Upload the source GIF to storage
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/input.gif" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/octet-stream" \
     --data-binary @path/to/local/input.gif
# 3. Add text overlay to the GIF
curl -X POST "https://api.groupdocs.cloud/v2.0/watermark/add" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
           "fileInfo": { "filePath": "input.gif", "storageName": "MyStorage" },
           "outputFileInfo": { "filePath": "output.gif", "storageName": "MyStorage" },
           "options": {
               "text": "Sample Watermark",
               "fontFamily": "Arial",
               "fontSize": 24,
               "color": "#FF0000",
               "opacity": 0.5,
               "horizontalAlignment": "Center",
               "verticalAlignment": "Middle",
               "pageRange": "1-"
           }
         }'
# 4. Download the watermarked GIF
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/output.gif" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o path/to/local/output.gif

有關請求正文和回應格式的更多詳細資訊,請參閱官方 API 文檔。

分解使用 REST 在 Java 中為 GIF 添加文字覆蓋 - 工作原理

  1. 初始化 API 用戶端 - new Configuration("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET") 會建立一個保存您憑證的配置物件。WatermarkApi 實例使用此配置來簽署每個請求。
Configuration config = new Configuration("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");
WatermarkApi watermarkApi = new WatermarkApi(config);
  1. 指定來源和目標檔案 - FileInfo 和 OutputFileInfo 告訴服務從哪裡讀取原始 GIF 以及將結果寫入哪裡。兩者都可以引用自訂的儲存名稱。

    FileInfo inputFile = new FileInfo();
    inputFile.setFilePath("input.gif");
    inputFile.setStorageName("MyStorage");
    
  2. 配置文字水印 - TextWatermarkOptions 包含所有視覺屬性:文字、字體、大小、顏色、不透明度、旋轉和對齊方式。將 pageRange 設置為 "1-" 可確保動畫 GIF 的每一幀都會收到疊加。

TextWatermarkOptions textOptions = new TextWatermarkOptions();
textOptions.setText("Sample Watermark");
textOptions.setFontFamily("Arial");
textOptions.setFontSize(24.0);
textOptions.setColor("#FF0000");
textOptions.setOpacity(0.5);
textOptions.setHorizontalAlignment(HorizontalAlignment.CENTER);
textOptions.setVerticalAlignment(VerticalAlignment.MIDDLE);
textOptions.setPageRange("1-");
  1. 建立並發送請求 - AddWatermarkRequest 將檔案資訊和選項打包。呼叫 watermarkApi.addWatermark(request) 會在伺服器上執行操作,並返回已處理檔案的路徑。

    AddWatermarkRequest request = new AddWatermarkRequest();
    request.setFileInfo(inputFile);
    request.setOutputFileInfo(outputFile);
    request.setOptions(textOptions);
    AddWatermarkResponse response = watermarkApi.addWatermark(request);
    
  2. 處理回應 - 回應包含輸出檔案路徑。在實際應用中,您通常會下載該檔案或將路徑傳遞給其他服務。

如需完整的類別和屬性列表,請參閱 API 參考。

安裝與設定 GroupDocs.Watermark Cloud SDK for Java

將 Maven 依賴項添加到您的 pom.xml(或等效的 Gradle 條目)。這將引入 SDK 的 23.8 版。

<dependency>
    <groupId>com.groupdocs</groupId>
    <artifactId>groupdocs-watermark-cloud</artifactId>
    <version>23.8</version>
</dependency>

先決條件

  • Java 8 或更高
  • 有效的 GroupDocs Cloud 帳戶
  • Client ID 和 Client Secret(可在 GroupDocs Cloud 儀表板中獲得)

配置範例

Configuration config = new Configuration("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");

從下載頁面下載最新的 JAR。對於生產環境,請使用從臨時許可證頁面獲得的有效許可證。

結論

使用 REST 在 Java 中為 GIF 添加文字覆蓋,借助 GroupDocs.Watermark Cloud SDK for Java 成為可重複的伺服器端操作。該 SDK 抽象化了處理動畫幀的複雜性,讓您專注於字幕或促銷訊息的內容。整合示例代碼或 cURL 工作流程後,您可以微調字體樣式、顏色和不透明度,以符合您的品牌。請記得取得正式授權,產品頁面上提供了授權價格資訊,亦可透過 臨時授權頁面 獲得測試用的臨時授權。祝開發愉快!

常見問題

  • 如何在 Java 中使用 REST 向 GIF 添加文字覆蓋,且文字會根據使用者變更?
    在執行時使用使用者特定的字串建立 TextWatermarkOptions 物件,然後呼叫相同的 addWatermark 方法。API 會獨立處理每個請求,因此完全支援動態內容。

  • 我可以在不影響動畫 GIF 速度的情況下添加字幕嗎?
    是的。水印會應用於每個幀,同時保留原始幀延遲。只需將 pageRange 設置為 "1-",即可讓每個幀都收到相同的覆蓋。

  • 什麼格式支援覆蓋文字顏色?
    SDK 接受 HEX 顏色代碼(例如 #FF0000)以及標準的 HTML 顏色名稱。請參閱 API reference 以獲取完整列表。

  • 我需要開發和測試的授權嗎?
    臨時授權足以用於評估和測試。對於正式部署,請從產品頁面購買完整授權,並使用 SDK 的授權 API 進行應用。

閱讀更多