Consistent Characters
Keep an anime character the same across images with the PixAI API. Pass up to three reference images to Tsubaki.3 and say in the prompt what to take from each.
Send reference images in contextImages of POST /v2/image/create, and Tsubaki.3 draws from them: the same character in a new scene, a character from one image in the pose of another, or a small edit to an image you already like.
Base URL: https://api.pixai.art/v2. Send Authorization: Bearer YOUR_API_KEY with every request; see How can I use PixAI API? to get a key.
Reference images work with Tsubaki.3 only (modelVersionId 2024383379556065549). Send up to 3, each under 4000 px on both sides.
Steps
Get a media ID for each reference
contextImages takes media IDs. An image you generated already has one in outputs.mediaIds of its task, so generate your character once and reuse that ID for every later image.
To use your own file, upload it: ask for an upload URL, PUT the bytes, then register it. The registered id is the media ID.
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": "...", "externalId": "..."}
curl -X PUT "UPLOAD_URL" -H "Content-Type: image/png" --data-binary @character.png
curl -X POST https://api.pixai.art/v2/media/image/register \
-H "Authorization: Bearer $PIXAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"externalId": "EXTERNAL_ID"}'
# → {"id": "MEDIA_ID", "type": "IMAGE", ...}Write the prompt
Refer to the references as image1, image2 and image3, in the order of contextImages. Write instructions in English sentences: what to make, and what to keep from each image.
| Goal | Example prompt |
|---|---|
| Same character, new scene | Draw the girl from image1 sitting in a café by the window on a rainy day. Keep her face, hair and outfit exactly as in image1. |
| Character in another pose | Redraw the character in image1 in the pose shown in image2. Keep her outfit, hair color and face exactly as in image1. |
| Edit one detail | Change the girl's navy coat to a bright red coat. Keep everything else in image1 as it is: her face, hair, pose and the background. |
For an edit, name what must stay the same. Anything the prompt leaves out may change.
Create the image
curl -X POST https://api.pixai.art/v2/image/create \
-H "Authorization: Bearer $PIXAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"modelVersionId": "2024383379556065549",
"contextImages": ["CHARACTER_MEDIA_ID", "POSE_MEDIA_ID"],
"prompt": "Redraw the character in image1 in the pose shown in image2. Keep her outfit, hair color and face exactly as in image1. Anime illustration, soft cel shading.",
"aspectRatio": "2:3"
}'Then poll GET /v2/task/{id} until status is completed and download outputs.mediaUrls, as in Your First API Call.
A media ID that does not exist answers 404 FILE_NOT_FOUND.
Ask for the same aspect ratio as the reference. In our tests, a portrait reference with "aspectRatio": "3:2" came back as a portrait picture between empty bars that filled more than half of the width.
Chain the results
Every finished image has its own media ID. Pass it back in contextImages to build a series from one character: generate a reference sheet once, then use it in every scene.
Full script
Generate a character, then two more scenes with that character as the reference. Set PIXAI_API_KEY in your environment first.
With requests installed:
import os
import time
import requests
API = "https://api.pixai.art/v2"
HEADERS = {"Authorization": f"Bearer {os.environ['PIXAI_API_KEY']}"}
TSUBAKI_3 = "2024383379556065549"
def generate(prompt, context_images=(), aspect_ratio="2:3"):
"""Create an image, wait for it, and return the task."""
body = {"modelVersionId": TSUBAKI_3, "prompt": prompt, "aspectRatio": aspect_ratio}
if context_images:
body["contextImages"] = list(context_images)
resp = requests.post(f"{API}/image/create", headers=HEADERS, json=body)
resp.raise_for_status()
task = resp.json()
while task["status"] in ("waiting", "running"):
time.sleep(2)
resp = requests.get(f"{API}/task/{task['id']}", headers=HEADERS)
if resp.status_code == 404: # A new task can answer 404 for a moment. Keep polling.
continue
resp.raise_for_status()
task = resp.json()
if task["status"] != "completed":
raise SystemExit(f"Task ended as {task['status']}: {task.get('taskStatusMsgI18n')}")
return task
def save(task, name):
url = task["outputs"]["mediaUrls"][0]
with open(name, "wb") as f:
f.write(requests.get(url).content)
character = generate(
"A full-body anime illustration of a girl with short silver hair and blue eyes, "
"wearing a navy coat and a red scarf, standing on a plain white background."
)
save(character, "character.webp")
ref = character["outputs"]["mediaIds"][0]
scenes = {
"cafe.webp": "Draw the girl from image1 reading a book in a café by the window on a rainy day. "
"Keep her face, hair and outfit exactly as in image1.",
"beach.webp": "Draw the girl from image1 walking along a beach at sunset, carrying her coat. "
"Keep her face, hair and scarf exactly as in image1.",
}
for name, prompt in scenes.items():
save(generate(prompt, context_images=[ref], aspect_ratio="2:3"), name)For Node.js 20 or later, saved as characters.mjs:
import { 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',
};
const TSUBAKI_3 = '2024383379556065549';
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();
}
// A task can answer 404 for a moment right after it is created: keep polling.
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 generate(prompt, contextImages = [], aspectRatio = '2:3') {
const body = { modelVersionId: TSUBAKI_3, prompt, aspectRatio };
if (contextImages.length) body.contextImages = contextImages;
let task = await call('/image/create', { method: 'POST', body: JSON.stringify(body) });
while (task.status === 'waiting' || task.status === 'running') {
await new Promise((resolve) => setTimeout(resolve, 2000));
task = (await poll(task.id)) ?? task;
}
if (task.status !== 'completed') {
throw new Error(`Task ended as ${task.status}: ${JSON.stringify(task.taskStatusMsgI18n)}`);
}
return task;
}
async function save(task, name) {
const res = await fetch(task.outputs.mediaUrls[0]);
await writeFile(name, Buffer.from(await res.arrayBuffer()));
}
const character = await generate(
'A full-body anime illustration of a girl with short silver hair and blue eyes, ' +
'wearing a navy coat and a red scarf, standing on a plain white background.',
);
await save(character, 'character.webp');
const ref = character.outputs.mediaIds[0];
const scenes = {
'cafe.webp':
'Draw the girl from image1 reading a book in a café by the window on a rainy day. ' +
'Keep her face, hair and outfit exactly as in image1.',
'beach.webp':
'Draw the girl from image1 walking along a beach at sunset, carrying her coat. ' +
'Keep her face, hair and scarf exactly as in image1.',
};
for (const [name, prompt] of Object.entries(scenes)) {
await save(await generate(prompt, [ref], '2:3'), name);
}Other ways to keep a character consistent
- A LoRA trained on the character, applied with
loras. See Find and use a model or LoRA. - The same
seedwith a small change to the prompt, which keeps the composition close but not the character's details. - Inpainting to change one area and leave the rest untouched. See Inpainting and Outpainting.
Reference
Image to Video
Turn a still image into a video clip with the PixAI API. Upload or reuse an image, set the first and last frame, add sound, and download the MP4.
Inpainting and Outpainting
Redraw part of an image, extend it past its edges, or redraw the whole image with the PixAI API. How to make the mask, upload it, and create the task.