Beispiel: Bild-zu-Video-Generierung

Vollständiges Beispiel zur Videoerstellung aus Bildern mit der Atlas Cloud API

Überblick

Dieses Tutorial zeigt einen vollständigen Bild-zu-Video-Workflow: Quellbild hochladen, ein Video daraus generieren und das Ergebnis abrufen.

Voraussetzungen

  • Ein Atlas Cloud-Konto mit API-Schlüssel
  • Eine Quellbilddatei (JPEG, PNG oder WebP)
  • Python 3.7+ mit requests-Bibliothek

Vollständiges Python-Beispiel

import requests
import time
import os

API_KEY = os.environ.get("ATLASCLOUD_API_KEY", "your-api-key")
BASE_URL = "https://api.atlascloud.ai/api/v1"

def upload_image(file_path):
    """Ein lokales Bild hochladen und eine temporäre URL erhalten."""
    with open(file_path, "rb") as f:
        response = requests.post(
            f"{BASE_URL}/model/uploadMedia",
            headers={"Authorization": f"Bearer {API_KEY}"},
            files={"file": f}
        )
    response.raise_for_status()
    url = response.json().get("url")
    print(f"Uploaded: {url}")
    return url

def generate_video(image_url, prompt, model="kling-v2.0"):
    """Eine Videogenerierungsaufgabe aus einem Bild einreichen."""
    response = requests.post(
        f"{BASE_URL}/model/generateVideo",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": model,
            "prompt": prompt,
            "image_url": image_url
        }
    )
    response.raise_for_status()
    return response.json().get("predictionId")

def wait_for_result(prediction_id, interval=5, timeout=300):
    """Auf Generierungsergebnis mit Timeout pollen."""
    elapsed = 0
    while elapsed < timeout:
        response = requests.get(
            f"{BASE_URL}/model/getResult?predictionId={prediction_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        )
        result = response.json()
        status = result.get("status")

        if status == "completed":
            return result.get("output")
        elif status == "failed":
            raise Exception(f"Failed: {result.get('error')}")

        print(f"  Status: {status} ({elapsed}s)")
        time.sleep(interval)
        elapsed += interval

    raise TimeoutError("Generation timed out")

# Schritt 1: Quellbild hochladen
print("Step 1: Uploading image...")
image_url = upload_image("my_photo.jpg")

# Schritt 2: Video generieren
prompt = "The person slowly turns their head and smiles, camera zooms in slightly"
print(f"Step 2: Generating video with prompt: {prompt}")
prediction_id = generate_video(image_url, prompt)
print(f"Task submitted: {prediction_id}")

# Schritt 3: Auf Ergebnis warten
print("Step 3: Waiting for video...")
video_url = wait_for_result(prediction_id)
print(f"Video ready: {video_url}")

Vollständiges Node.js-Beispiel

import fs from "fs";

const API_KEY = process.env.ATLASCLOUD_API_KEY || "your-api-key";
const BASE_URL = "https://api.atlascloud.ai/api/v1";

async function uploadImage(filePath) {
  const formData = new FormData();
  formData.append("file", new Blob([fs.readFileSync(filePath)]));

  const response = await fetch(`${BASE_URL}/model/uploadMedia`, {
    method: "POST",
    headers: { Authorization: `Bearer ${API_KEY}` },
    body: formData,
  });

  if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
  const { url } = await response.json();
  console.log(`Uploaded: ${url}`);
  return url;
}

async function generateVideo(imageUrl, prompt, model = "kling-v2.0") {
  const response = await fetch(`${BASE_URL}/model/generateVideo`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model, prompt, image_url: imageUrl }),
  });

  if (!response.ok) throw new Error(`Generate failed: ${response.status}`);
  return (await response.json()).predictionId;
}

async function waitForResult(predictionId, interval = 5000, timeout = 300000) {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    const response = await fetch(
      `${BASE_URL}/model/getResult?predictionId=${predictionId}`,
      { headers: { Authorization: `Bearer ${API_KEY}` } }
    );
    const result = await response.json();

    if (result.status === "completed") return result.output;
    if (result.status === "failed") throw new Error(result.error);

    console.log(`  Status: ${result.status}`);
    await new Promise((r) => setTimeout(r, interval));
  }
  throw new Error("Timeout");
}

// Workflow ausführen
console.log("Step 1: Uploading image...");
const imageUrl = await uploadImage("my_photo.jpg");

console.log("Step 2: Generating video...");
const predictionId = await generateVideo(
  imageUrl,
  "The person slowly turns and smiles, gentle camera movement"
);

console.log("Step 3: Waiting for result...");
const videoUrl = await waitForResult(predictionId);
console.log(`Video ready: ${videoUrl}`);

Tipps

  • Videomodelle: Verschiedene Modelle haben unterschiedliche Stärken — Kling für Qualität, Seedance für Bewegung, Vidu für kinematischen Stil
  • Prompt für Bewegung: Beschreiben Sie die gewünschte Bewegung, Kamerabewegung und Szenenwechsel
  • Bildqualität: Qualitativ hochwertigere Quellbilder erzeugen in der Regel bessere Videoergebnisse
  • Generierungszeit: Die Videogenerierung dauert je nach Modell und Parametern typischerweise 30 Sekunden bis 3 Minuten
  • Polling-Intervall: Verwenden Sie 5-Sekunden-Intervalle für Video (vs. 2 Sekunden für Bilder), um unnötige API-Aufrufe zu reduzieren

Nächste Schritte