AionRouter Image Generation and Editing API Guide

Image APIs turn descriptions into images and, when supported by the model, accept reference images or edit existing ones. Text-to-image, reference generation and inpainting may require different inputs. Choose the operation first, then its model and endpoint, before copying parameters.

This guide includes cURL, Windows PowerShell/CMD and Python examples, image saving, parameter choices and application integration details. The existence of an endpoint does not mean every model supports every image feature. Verify availability using your key and model details.

Choose text-to-image, references or editing

Desired operation Inputs to prepare What to check in the model
Product images, illustrations or creative drafts Prompt and target layout Generation endpoint, size, quality and output format
Recompose an existing product image Reference and instructions on what to preserve or change Reference input, count, format and size limits
Change a background or local area Original image and a mask if required Editing protocol, mask support and interpretation
Generate several candidates for an app Prompt and explicit output count Count limits, returned items and billing

Start small: generate or edit one image, check content, layout and format, then increase quality, count or references. Validate product images, posters, character consistency and image text with your own samples rather than relying on demonstration images.

Choose a model and endpoint

Task Common endpoint Check before calling
Generate from text /v1/images/generations Model ID, dimensions, count and response format
Generate from reference images Some models still use /v1/images/generations Reference fields, URL/Base64 support and image limits
Edit or inpaint an image /v1/images/edits for compatible models JSON or multipart, image fields and mask support
Stream generation progress The endpoint of a streaming-capable model stream support, events and partial-image capability

Reference-image generation and masked inpainting are different capabilities. Support for the former does not imply support for /images/edits or masks.

There is no public /v1/tasks/{id} polling contract shared by all image models. Do not apply video polling to images, or treat /v1/images/variations as an implemented image-variation feature.

Set up and generate your first image

Prepare the key and model

Create a key in API Key management, choose an image model in the Model Marketplace, and copy its actual ID. It must be accessible to the account and key.

Terminal compatibility

Use the examples for your shell: macOS/Linux use Bash or Zsh; Windows uses PowerShell or CMD. Git Bash/WSL can use the Bash examples, but run all setup and requests in the same environment. The current API root is https://test.aionrouter.io.

Windows examples explicitly use curl.exe to avoid the curl alias in Windows PowerShell 5.1. Check curl --version or curl.exe --version; --fail-with-body requires cURL 7.76.0 or later. Microsoft: curl on Windows · cURL options

Run one shell variant only. Environment variables apply to that terminal and programs started from it. In CMD, run each line separately; at the AIONROUTER_BASE_URL prompt, paste the API root shown above, without a trailing slash. Then enter the actual key, model or voice when prompted. Do not paste Bash export, backslash continuations or heredocs into CMD or PowerShell.

macOS / Linux — Bash / Zsh

export AIONROUTER_BASE_URL='https://test.aionrouter.io'
export AIONROUTER_API_KEY='替换为控制台复制的完整密钥'
export AIONROUTER_IMAGE_MODEL='替换为支持图像生成的实际模型 ID'

Windows — PowerShell

$env:AIONROUTER_BASE_URL = 'https://test.aionrouter.io'
$env:AIONROUTER_API_KEY = Read-Host 'AIONROUTER_API_KEY'
$env:AIONROUTER_IMAGE_MODEL = Read-Host 'AIONROUTER_IMAGE_MODEL'

Windows — CMD

set "AIONROUTER_BASE_URL="
set /p "AIONROUTER_BASE_URL=AIONROUTER_BASE_URL: "
set "AIONROUTER_API_KEY="
set /p "AIONROUTER_API_KEY=AIONROUTER_API_KEY: "
set "AIONROUTER_IMAGE_MODEL="
set /p "AIONROUTER_IMAGE_MODEL=AIONROUTER_IMAGE_MODEL: "

Use the console's API root without a trailing slash.

Make a first text-to-image request with cURL

macOS / Linux — Bash / Zsh

curl --fail-with-body --silent --show-error \
  "$AIONROUTER_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $AIONROUTER_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<JSON
{
  "model": "$AIONROUTER_IMAGE_MODEL",
  "prompt": "一只白色陶瓷杯放在浅色木桌上,窗边自然光,近景产品摄影,背景简洁,不添加文字。",
  "n": 1
}
JSON

Windows request body: image-generation-2.json

Save this JSON in the current directory as UTF-8 without BOM, replacing YOUR_... values with actual model IDs or other required values. JSON files do not expand environment variables: changing a terminal model variable does not change this file. Do not use Windows PowerShell 5.1 > to create it, because that defaults to UTF-16LE. Both Windows commands below read the same file. Microsoft: character encoding

{
  "model": "YOUR_AIONROUTER_IMAGE_MODEL",
  "prompt": "一只白色陶瓷杯放在浅色木桌上,窗边自然光,近景产品摄影,背景简洁,不添加文字。",
  "n": 1
}

Windows — PowerShell

curl.exe --fail-with-body --silent --show-error "${env:AIONROUTER_BASE_URL}/v1/images/generations" -H "Authorization: Bearer ${env:AIONROUTER_API_KEY}" -H 'Content-Type: application/json' --data-binary '@image-generation-2.json'

Windows — CMD

curl.exe --fail-with-body --silent --show-error "%AIONROUTER_BASE_URL%/v1/images/generations" -H "Authorization: Bearer %AIONROUTER_API_KEY%" -H "Content-Type: application/json" --data-binary "@image-generation-2.json"

This example omits model-specific size, quality and response settings. After a successful basic call, add those fields according to the selected model.

A typical OpenAI-compatible response contains image URLs or Base64 data in data. These excerpts illustrate both shapes; not every model supports both return modes.

{
  "data": [
    {
      "url": "https://assets.example.com/generated-image.png"
    }
  ]
}
{
  "data": [
    {
      "b64_json": "BASE64_ENCODED_IMAGE_DATA"
    }
  ]
}

b64_json contains Base64-encoded image bytes, not JSON after decoding. A url requires a separate download. Link expiration depends on the service; promptly save images you need to keep.

What counts as a successful first call? Beyond a successful response, read the actual image: inspect the result array, save each item, open the files and check their content. Confirm the prompt, expected count and usable dimensions before moving to batches.

When moving a terminal example into backend code, preserve its protocol and fields. Image input for a chat model is not automatically image generation, and a console playground submission URL is not the external API endpoint.

Read, download and save results

Save returned images with Python

This standard-library example handles url and b64_json, saving files as image-1, image-2, and so on. It does not assume a file extension: add .png, .jpg or .webp after checking the actual format.

import base64
import json
import os
from pathlib import Path
import urllib.error
import urllib.request

base_url = os.environ["AIONROUTER_BASE_URL"].rstrip("/")
request = urllib.request.Request(
    f"{base_url}/v1/images/generations",
    data=json.dumps({
        "model": os.environ["AIONROUTER_IMAGE_MODEL"],
        "prompt": "木桌上的白色陶瓷杯,柔和自然光,产品摄影。",
        "n": 1,
    }, ensure_ascii=False).encode("utf-8"),
    headers={
        "Authorization": f"Bearer {os.environ['AIONROUTER_API_KEY']}",
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urllib.request.urlopen(request, timeout=300) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print("HTTP", error.code)
    print(error.read().decode("utf-8", errors="replace"))
    raise SystemExit(1)

images = result.get("data", [])
if isinstance(images, dict):
    images = [images]
if not images:
    raise RuntimeError("响应中没有图片,请检查返回的错误或模型响应格式。")

for index, image in enumerate(images, start=1):
    if image.get("b64_json"):
        content = base64.b64decode(image["b64_json"], validate=True)
    elif image.get("url"):
        # 下载图片时不附带 AionRouter 密钥。
        with urllib.request.urlopen(image["url"], timeout=120) as response:
            content = response.read()
    else:
        raise RuntimeError(f"第 {index} 项没有 url 或 b64_json。")
    target = Path(f"image-{index}")
    target.write_bytes(content)
    print("已保存", target)

Run the Python example on macOS or Windows

Save the code as example.py in UTF-8. In the terminal where you set the variables above, use python3 example.py on macOS/Linux or py -3 example.py on Windows. If the Windows launcher is unavailable but Python 3 is installed, use python example.py. The standard-library code is shared; variables set in PowerShell, CMD and WSL are not automatically shared.

Generation time depends on model, resolution, count and channel load. The timeouts are client settings, not delivery guarantees. Production batches should also handle failed downloads, expired URLs and missing images.

URLs and Base64 need different saving flows. Download a returned url before it expires. Decode b64_json before writing binary bytes. Do not save the JSON body as PNG or write Base64 text directly as an image file.

Check for nonempty content, its actual media type and matching extension. Examples demonstrate downloading, but production naming must follow the actual format instead of forcing every file to one extension. Save multiple items individually and link each file to its business request.

External URLs may expire or depend on network access and permissions. If downloading fails, retry the existing result first instead of generating again. Send the platform key only to gateway requests that require it, never to arbitrary third-party image storage hosts.

For product displays or long-lived article images, copy approved files into storage you control and retain their business associations. Temporary provider URLs are not permanent CDN addresses.

Use references, local editing and consistency constraints

Reference images with Qwen Image 3.0

If qwen-image-3.0 or qwen-image-3.0-pro is available to your account, its JSON generation endpoint accepts references through image, rather than the multipart edit endpoint.

Use this body with POST /v1/images/generations. Replace the URL with an image the generation service can access. If the public model uses an alias, use that actual ID too.

{
  "model": "qwen-image-3.0",
  "prompt": "保留参考图中杯子的形状和颜色,将背景改为有自然光的浅色厨房台面。",
  "image": [
    "https://assets.example.com/cup-reference.png"
  ],
  "size": "1024x1024",
  "n": 1
}

The current integration rules for these two models include:

  • n from 1 to 6, with at most 3 reference images.
  • References as supported URL or Base64 strings; use an array for multiple images.
  • JSON requests to /v1/images/generations, not /v1/images/edits or multipart.
  • No stream: true or mask support.
  • size accepts auto or valid pixel dimensions; area ranges from 512² to 2048², with aspect ratio from 1:8 to 8:1.

These rules apply to the Qwen Image 3.0 family, not all Qwen, Seedream, GPT Image or other models. Availability still depends on the key's model list and model details.

Image editing and inpainting

For a model explicitly supporting the OpenAI multipart edit protocol, upload a local image:

macOS / Linux — Bash / Zsh

curl --fail-with-body --silent --show-error \
  "$AIONROUTER_BASE_URL/v1/images/edits" \
  -H "Authorization: Bearer $AIONROUTER_API_KEY" \
  -F 'model=YOUR_EDIT_MODEL_ID' \
  -F 'image=@./input.png' \
  -F 'prompt=保留主体,把背景改为浅蓝色。' \
  -F 'n=1'

Windows — PowerShell

curl.exe --fail-with-body --silent --show-error "${env:AIONROUTER_BASE_URL}/v1/images/edits" -H "Authorization: Bearer ${env:AIONROUTER_API_KEY}" -F 'model=YOUR_EDIT_MODEL_ID' -F 'image=@./input.png' -F 'prompt=保留主体,把背景改为浅蓝色。' -F 'n=1'

Windows — CMD

curl.exe --fail-with-body --silent --show-error "%AIONROUTER_BASE_URL%/v1/images/edits" -H "Authorization: Bearer %AIONROUTER_API_KEY%" -F "model=YOUR_EDIT_MODEL_ID" -F "image=@./input.png" -F "prompt=保留主体,把背景改为浅蓝色。" -F "n=1"

Replace YOUR_EDIT_MODEL_ID with an actual compatible model and prepare input.png. Let cURL generate multipart Content-Type and its boundary.

Inpainting additionally requires model support for mask and a compliant mask file. Transparency interpretation, dimensions, file size and formats depend on the model; one rule set does not cover all providers.

Make references accessible first. File uploads, public URLs and Base64 are different inputs; use only the model's supported method. A URL requiring login, an expired grant or access to a private network may work in your browser while remaining unreadable to the generation service.

State what must stay unchanged. For example, “keep the cup's shape, color and logo placement; change only the background and lighting” is easier to review than “regenerate based on this image”. Fix the references, model version and key parameters, then change one condition per comparison.

Not every image-to-image task needs or supports a mask. A reference upload does not establish precise inpainting support. Adding a mask field cannot create that capability. Prepare edges, transparency and corresponding dimensions according to the model's contract.

Choose size, count, quality and prompts

Common request parameters

Parameter Type Meaning
model string Actual accessible image model ID
prompt string Description of the desired image
n integer Output count; start with 1, with higher values subject to model limits
size string Accepted dimensions, commonly 1024x1024 using the letter x
quality string A quality level supported by that model
response_format string A supported mode such as url or b64_json
image / images Model-specific Reference fields with model-specific meanings and structures
mask Model-specific Inpainting mask, only for explicitly supported models and protocols
stream boolean Streaming, when supported by both model and channel

The gateway has a safety ceiling for abnormal counts, but it is not a model's business limit. Do not infer that a model accepts dozens or hundreds of images; follow its lower limit.

Do not put a ratio such as 16:9 into a size field that only accepts pixel dimensions. Some models support auto, a ratio field or other conventions; follow their details.

Write more controllable prompts

Specify the subject, setting, composition, lighting and details to preserve. A product prompt can say “white ceramic cup, light wooden table, close-up, natural sidelight, simple background” rather than only “a premium product image”.

For text in an image, provide the exact wording and test the model's text capability. Accuracy depends on model, language, length and layout; no fixed prompt technique guarantees correct text.

For reference tasks, state what must remain unchanged and what may change. Use seeds only where supported, and retain the model version, dimensions and complete request. The same seed does not guarantee an identical result.

Choose output for its destination. Decide on square, landscape or portrait first, then check whether the model accepts pixel dimensions, ratios or presets. For exact dimensions, inspect the downloaded file and crop or resize in your own post-processing if needed.

Review text inside images separately. Supply exact wording, language and placement, then inspect numbers, brand names and small print. Add important prices, dates and legal wording as editable design text when appropriate instead of publishing generated typos.

Track differences between batch variants. Version prompts and parameter combinations and retain result IDs and review decisions. The same prompt and seed do not guarantee exact reproduction. Save the original file when you need to reuse an image.

Check usage, timeouts and console differences

Pricing and troubleshooting

Charges may depend on image count, resolution, quality, reference inputs or input/output tokens. Review model details and pricing before selecting dimensions and batch size. A supplier's public price is not necessarily AionRouter's selling price.

Symptom Action
model is required or model unavailable Check the actual ID, key restrictions and accessible group
Invalid size Use supported dimensions and the letter x; do not mix ratios with pixels
Count exceeds limits Verify with n: 1, then increase within the model's limit
Edit or streaming request rejected Confirm that model supports the endpoint and parameters
Image URL cannot be downloaded Check expiration, networking and storage permissions; do not create new generations just to diagnose downloads
Request times out Keep the request ID and check results and usage first; resubmission may incur a new charge

Consumption and delivery are separate stages. Download, layout or review failure after generation does not prove the generation used nothing. Distinguish rejected parameters, generation failure, download failure and business rejection before deciding to call again.

Manage playground history and external API results separately. Web image tasks have their own history and asset handling. Your application must receive and save external API results. Do not assume they enter playground history or receive the same archival treatment.

Check existing information after a network interruption. Retain the timestamp, model, error body and available request ID. This guide does not promise uniform idempotent retries or public task queries across all image endpoints. Do not regenerate endlessly when submission status is uncertain.

FAQ and further integration

Frequently asked questions

Can I switch every image model by changing only its name?

Minimal text-to-image requests share fields, but dimensions, references, masks, quality, streaming and return formats can differ. Verify these again after switching models.

Is there a common asynchronous image polling API?

This guide defines no such universal contract. Some channels handle asynchronous providers internally, but that does not establish one public polling API for every image model.

Should I use URLs or Base64 for storage?

Both ultimately require saving the image to your own storage. URLs need another download; Base64 needs decoding and enlarges JSON bodies. First check which format the model supports.

Can images be used commercially, and do they contain watermarks?

Check the chosen model, provider and applicable platform terms. The API itself does not establish a universal copyright, likeness-rights or watermark policy.

Why does the same reference produce different images? It is only one input; the model, prompt, dimensions and supported parameters also matter. Save approved files and record generation conditions for stable business assets.

Can generated images go straight into product pages or ads? Check accuracy, text, brand and likeness requirements, and the model's applicable terms. API success does not replace content review or provide universal commercial authorization.

Related guides