이미지로 동영상 만들기
PixAI API로 정지 이미지를 동영상으로 만듭니다. 이미지를 업로드하거나 재사용하고, 첫 프레임과 마지막 프레임을 지정하고, 사운드를 추가한 뒤 MP4를 다운로드하는 방법을 안내합니다.
POST /v2/frame-video/create는 PixAI의 Tsubaki 동영상 모델로 이미지를 움직이게 합니다. 동영상은 지정한 이미지에서 시작하며, 두 번째 이미지를 보내면 그 이미지에서 끝납니다. 일러스트에 움직임을 주거나, 두 이미지 사이의 전환을 만들거나, 루프 영상을 만들 때 사용하세요.
기본 URL: https://api.pixai.art/v2. 모든 요청에 Authorization: Bearer YOUR_API_KEY를 추가하세요. API 키 발급 방법은 PixAI API를 사용하려면?을 참고하세요.
이미지 기반 동영상 생성에는 PixAI 멤버십이 필요합니다. 크레딧은 작업이 생성될 때 차감되며, 동영상 생성에는 몇 분 정도 걸립니다.
단계
이미지의 미디어 ID 준비
동영상의 프레임은 미디어 ID로 지정합니다. API로 생성한 이미지에는 이미 미디어 ID가 있습니다. 완료된 작업의 outputs.mediaIds에 들어 있으므로 다음 단계로 넘어가도 됩니다.
직접 가진 파일을 사용하려면 세 번의 호출로 업로드합니다. 먼저 업로드 URL을 요청합니다.
curl -X POST https://api.pixai.art/v2/media/image/upload-url \
-H "Authorization: Bearer $PIXAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'{
"uploadUrl": "https://...",
"externalId": "3f2b8c1e-6a4d-4f6e-9b1a-2c7d5e8f9a01"
}파일의 원본 바이트를 실제 Content-Type과 함께 uploadUrl에 PUT합니다. multipart 폼으로 보내지 마세요.
curl -X PUT "UPLOAD_URL" \
-H "Content-Type: image/png" \
--data-binary @first-frame.png그다음 업로드한 파일을 등록합니다. 응답의 id가 미디어 ID입니다.
curl -X POST https://api.pixai.art/v2/media/image/register \
-H "Authorization: Bearer $PIXAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"externalId": "3f2b8c1e-6a4d-4f6e-9b1a-2c7d5e8f9a01"}'동영상 작업 생성
미디어 ID를 firstFrameMediaId로 보내고, prompt에 어떤 장면이 펼쳐질지 적습니다.
curl -X POST https://api.pixai.art/v2/frame-video/create \
-H "Authorization: Bearer $PIXAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "tbkv1.0.1",
"firstFrameMediaId": "MEDIA_ID",
"prompt": "she turns around and smiles, hair blowing in the wind",
"duration": 5
}'응답은 status: "waiting" 상태의 작업입니다. 응답의 id를 기록해 두세요.
작업 완료까지 대기
status가 completed, failed, cancelled 중 하나가 될 때까지 몇 초마다 GET /v2/task/{id}를 폴링합니다.
curl https://api.pixai.art/v2/task/TASK_ID \
-H "Authorization: Bearer $PIXAI_API_KEY"완료된 동영상 작업에서는 outputs.videoMediaId에 동영상이 들어 있습니다. outputs.mediaIds에는 포스터 이미지만 들어 있습니다.
{
"id": "TASK_ID",
"status": "completed",
"taskKind": "i2v-inhouse",
"outputs": {
"videoMediaId": "VIDEO_MEDIA_ID",
"mediaIds": ["POSTER_MEDIA_ID"]
}
}동영상 다운로드
GET /v2/media/batch로 동영상의 미디어 ID를 조회하고, MP4 파일인 fileUrl을 다운로드합니다.
curl "https://api.pixai.art/v2/media/batch?ids=VIDEO_MEDIA_ID" \
-H "Authorization: Bearer $PIXAI_API_KEY"
curl -L "FILE_URL" -o video.mp4생성된 미디어는 영구적으로 보관되지 않습니다. 작업이 완료되면 바로 동영상을 다운로드하세요.
옵션
| 필드 | 설명 |
|---|---|
model | tbkv1.0.1은 최신 Tsubaki 동영상 모델이고, tbkv1.0은 이전 모델입니다. |
lastFrameMediaId | 동영상이 끝나는 이미지입니다. 첫 프레임을 다시 보내면 루프 영상이 됩니다. |
duration | 5~15초(정수). 기본값은 5입니다. |
mode | basic(기본값) 또는 professional. professional은 tbkv1.0.1에서 1080p 업스케일이 추가되며 비용이 더 듭니다. |
generateAudio | 사운드트랙 생성 여부. 기본값은 true입니다. |
audioLanguage | 사운드트랙의 음성 언어: english, japanese, korean, chinese, 음성이 없으면 none. |
동영상은 첫 프레임의 종횡비를 유지합니다. 다른 사용자가 소유한 프레임을 지정하면 400 INVALID_REFERENCE_MEDIA로 거부됩니다.
정확한 프레임에서 시작하는 대신 여러 이미지, 동영상 클립, 오디오를 참고해 새로운 장면을 만들려면 POST /v2/reference-video/create를 사용하세요. Seedance 2, Vidu 등 다른 동영상 모델도 사용할 수 있습니다.
전체 스크립트
로컬 이미지를 업로드해 동영상으로 만들고 MP4로 저장합니다. 먼저 환경 변수 PIXAI_API_KEY를 설정하세요.
requests를 설치한 상태에서 실행합니다.
import os
import time
import requests
API = "https://api.pixai.art/v2"
HEADERS = {"Authorization": f"Bearer {os.environ['PIXAI_API_KEY']}"}
def upload_image(path, content_type="image/png"):
"""로컬 이미지를 업로드하고 미디어 ID를 반환합니다."""
target = requests.post(f"{API}/media/image/upload-url", headers=HEADERS, json={})
target.raise_for_status()
target = target.json()
with open(path, "rb") as f:
put = requests.put(target["uploadUrl"], data=f, headers={"Content-Type": content_type})
put.raise_for_status()
media = requests.post(
f"{API}/media/image/register",
headers=HEADERS,
json={"externalId": target["externalId"]},
)
media.raise_for_status()
return media.json()["id"]
def wait_for(task_id, interval=5):
"""작업이 끝날 때까지 폴링한 뒤 작업을 반환합니다."""
while True:
resp = requests.get(f"{API}/task/{task_id}", headers=HEADERS)
if resp.status_code != 404: # 생성 직후의 작업은 잠시 404를 반환할 수 있습니다. 계속 폴링합니다.
resp.raise_for_status()
task = resp.json()
if task["status"] not in ("waiting", "running"):
return task
time.sleep(interval)
first_frame = upload_image("first-frame.png")
resp = requests.post(
f"{API}/frame-video/create",
headers=HEADERS,
json={
"model": "tbkv1.0.1",
"firstFrameMediaId": first_frame,
"prompt": "she turns around and smiles, hair blowing in the wind",
"duration": 5,
},
)
resp.raise_for_status()
task = wait_for(resp.json()["id"])
if task["status"] != "completed":
raise SystemExit(f"Task ended as {task['status']}: {task.get('taskStatusMsgI18n')}")
video_id = task["outputs"]["videoMediaId"]
media = requests.get(f"{API}/media/batch", headers=HEADERS, params={"ids": video_id})
media.raise_for_status()
video = next(m for m in media.json() if m["id"] == video_id)
with open("video.mp4", "wb") as f:
f.write(requests.get(video["fileUrl"]).content)Node.js 20 이상에서 video.mjs로 저장해 실행합니다.
import { readFile, writeFile } from 'node:fs/promises';
const API = 'https://api.pixai.art/v2';
const HEADERS = {
Authorization: `Bearer ${process.env.PIXAI_API_KEY}`,
'Content-Type': 'application/json',
};
async function call(path, init = {}) {
const res = await fetch(`${API}${path}`, { headers: HEADERS, ...init });
if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
return res.json();
}
// 생성 직후의 작업은 잠시 404를 반환할 수 있으므로 계속 폴링합니다.
async function poll(taskId) {
const res = await fetch(`${API}/task/${taskId}`, { headers: HEADERS });
if (res.status === 404) return null;
if (!res.ok) throw new Error(`/task/${taskId}: ${res.status} ${await res.text()}`);
return res.json();
}
async function uploadImage(path, contentType = 'image/png') {
const { uploadUrl, externalId } = await call('/media/image/upload-url', {
method: 'POST',
body: '{}',
});
const put = await fetch(uploadUrl, {
method: 'PUT',
headers: { 'Content-Type': contentType },
body: await readFile(path),
});
if (!put.ok) throw new Error(`upload: ${put.status}`);
const media = await call('/media/image/register', {
method: 'POST',
body: JSON.stringify({ externalId }),
});
return media.id;
}
async function waitFor(taskId, interval = 5000) {
for (;;) {
const task = await poll(taskId);
if (task && task.status !== 'waiting' && task.status !== 'running') return task;
await new Promise((resolve) => setTimeout(resolve, interval));
}
}
const firstFrame = await uploadImage('first-frame.png');
const created = await call('/frame-video/create', {
method: 'POST',
body: JSON.stringify({
model: 'tbkv1.0.1',
firstFrameMediaId: firstFrame,
prompt: 'she turns around and smiles, hair blowing in the wind',
duration: 5,
}),
});
const task = await waitFor(created.id);
if (task.status !== 'completed') {
throw new Error(`Task ended as ${task.status}: ${JSON.stringify(task.taskStatusMsgI18n)}`);
}
const videoId = task.outputs.videoMediaId;
const media = await call(`/media/batch?ids=${videoId}`);
const video = media.find((m) => m.id === videoId);
const file = await fetch(video.fileUrl);
await writeFile('video.mp4', Buffer.from(await file.arrayBuffer()));