Example: Image-to-Video Generation
Complete example of creating videos from images using Atlas Cloud API
Overview
This tutorial demonstrates a complete image-to-video workflow: upload a source image, generate a video from it, and retrieve the result.
Prerequisites
- An Atlas Cloud account with API key
- A source image file (JPEG, PNG, or WebP)
- Python 3.7+ with
requestslibrary
Complete Python Example
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):
"""Upload a local image and get a temporary URL."""
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"):
"""Submit a video generation task from an image."""
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):
"""Poll for generation result with timeout."""
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")
# Step 1: Upload source image
print("Step 1: Uploading image...")
image_url = upload_image("my_photo.jpg")
# Step 2: Generate video
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}")
# Step 3: Wait for result
print("Step 3: Waiting for video...")
video_url = wait_for_result(prediction_id)
print(f"Video ready: {video_url}")Complete Node.js Example
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");
}
// Run the workflow
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}`);Tips
- Video models: Different models have different strengths — Kling for quality, Seedance for motion, Vidu for cinematic style
- Prompt for motion: Describe the desired movement, camera motion, and scene changes
- Image quality: Higher quality source images generally produce better video results
- Generation time: Video generation typically takes 30 seconds to 3 minutes depending on model and parameters
- Poll interval: Use 5-second intervals for video (vs 2 seconds for images) to reduce unnecessary API calls
Next Steps
- Text-to-Image Example — Generate source images with AI
- Video Generation Models — Explore all video models
- Upload Files — Learn more about file upload
- Predictions — Understanding async task flow