Qwen-Image API reference

更新时间:
复制 MD 格式

Qwen-Image is a general-purpose image generation model that supports multiple artistic styles and excels at complex text rendering. It handles multi-line layouts, paragraph-level text generation, and fine-grained detail rendering.

Quick access: User guide | Try it online (Beijing | Singapore) | Technical blog

Examples

Prompt

Generated image

A winter city street scene in Beijing. Two adjacent traditional Chinese shops stand side by side. One has bluish-gray tiled roofs and vermilion walls. Warm lanterns with paper-cut horse designs hang under the eaves. On an overcast day, soft diffused light casts gentle halos that reflect off the damp cobblestone pavement. To the left is a calligraphy shop. An indigo-blue aged signboard displays bold cursive script reading “Text Rendering”. A sign hangs on the shop’s glass door, written top to bottom in Tian Yingzhang’s hard-pen script: “Professional Slides, Bilingual Posters, Advanced Infographics”, with a red seal reading “1k token”. Three vertical calligraphy works hang on the shop wall: “Alibaba”, “Qwen”, and “Image Generation”. An elderly man with white hair stands with his back to the camera, viewing the display. To the right is a flower shop. Its signboard spells “Real Texture” using fresh flowers. Multi-tiered flower racks hold red roses, pink peonies, and green plants. A circular floral border label on the door reads “2k resolution”. A colorful neon sign near the entrance reads “Fine Detailing: People, Nature, Architecture”. Between the two shops sits a snowman holding an old-fashioned blackboard. Chalk on the board reads “Qwen-Image-2.0 Official Release”. On the left side of the street, a young couple leans close together. The woman has a slim face and wears an off-white cashmere coat and skin-tone tights. She holds a heart-shaped transparent balloon printed with white text: “Text-to-Image + Editing = One Tool”. Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool coat and a light-colored turtleneck sweater. On the right side of the street, a delivery rider speeds past, his backpack printed with “Smaller Model, Faster Speed”. Light and shadow interweave across the entire street. Motion and stillness balance each other.

image (10)

Model overview

Model

Description

Output image specifications

qwen-image-2.0-pro Recommended

Same capabilities as qwen-image-2.0-pro-2026-04-22

Qwen Pro series for image generation and editing. Offers stronger text rendering, realistic texture, and semantic adherence.

For image editing, see Qwen-Image Editing.

Resolution: Set width and height freely. Total pixels must be between 512×512 and 2048×2048. Default resolution is 2048×2048.

Format: PNG

Number of images: 1–6

qwen-image-2.0-pro-2026-04-22 Recommended

qwen-image-2.0-pro-2026-03-03

qwen-image-2.0 Recommended

Same capabilities as qwen-image-2.0-2026-03-03

Qwen accelerated series for image generation and editing. Balances quality and response speed.

For image editing, see Qwen-Image Editing.

qwen-image-2.0-2026-03-03 Recommended

qwen-image-max

Same capabilities as qwen-image-max-2025-12-30

Qwen Max series for image generation. Delivers higher realism and naturalness, with fewer AI-generation artifacts.

Resolution: See size parameter settings for supported resolutions and aspect ratios.

Format: PNG

Number of images: Fixed at 1

qwen-image-max-2025-12-30

qwen-image-plus

Same capabilities as qwen-image

Qwen Plus series for image generation. Excels at diverse artistic styles and text rendering.

qwen-image-plus-2026-01-09

qwen-image

Only qwen-image-plus and qwen-image support asynchronous calls .
Note

Before calling the API, check the supported models list for your region.

Prerequisites

Before making a call, get an API key and export the API key as an environment variable. To make calls using the SDK, install the DashScope SDK.

Important

The China (Beijing) and Singapore regions have separate API keys and request endpoints. They cannot be used interchangeably. Cross-region calls lead to authentication failures or service errors.

Synchronous API (recommended)

HTTP

Synchronous calls return results in a single request.

Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

When calling, replace WorkspaceId with your actual workspace ID.

Request parameters

Text-to-image

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-2.0-pro",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "text": "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow."
                    }
                ]
            }
        ]
    },
    "parameters": {
        "negative_prompt": "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
        "prompt_extend": true,
        "watermark": false,
        "size": "2048*2048"
    }
}'
Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Request body

model string (required)

Model name. Example: qwen-image-2.0-pro.

input object (required)

Input information.

Properties

messages array (required)

Array of message objects. Only single-turn conversations are supported, so the array must contain exactly one element.

Properties

role string (required)

Message role. Set to user.

content array (required)

Array of message content objects.

Properties

text string (required)

A positive prompt describing the image content, style, and composition you want.

Supports Chinese and English. The qwen-image-2.0 series accept up to 1,300 tokens. Other models accept up to 800 tokens. The system truncates excess tokens.

Note: Only one text field is allowed. Omitting it or providing more than one returns an error.

parameters object (optional)

Image processing parameters.

Properties

negative_prompt string (optional)

A negative prompt describing what you do not want in the image.

Supports Chinese and English. Maximum length is 500 characters. Excess characters are truncated automatically.

Example: Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth surfaces, AI-generated look. Chaotic composition. Blurry or distorted text.

size string (optional)

Output image resolution, formatted as width*height.

qwen-image-2.0 series models: Total pixels must be between 512×512 and 2048×2048. Default resolution is 2048×2048. Recommended resolutions:

  • 2688*1536: 16:9

  • 1536*2688: 9:16

  • 2048*2048 (default): 1:1

  • 2368*1728: 4:3

  • 1728*2368: 3:4

qwen-image-max and qwen-image-plus series models: Default resolution is 1664*928. Supported resolutions and their aspect ratios:

  • 1664*928 (default): 16:9

  • 1472*1104: 4:3

  • 1328*1328: 1:1

  • 1104*1472: 3:4

  • 928*1664: 9:16

n integer (optional)

Number of output images. Default is 1.

For qwen-image-2.0 series models, you can choose 1–6 images.

For qwen-image-max and qwen-image-plus series models, this value is fixed at 1. Setting any other value returns an error.

prompt_extend bool (optional)

Enable smart prompt rewriting. The model optimizes the positive prompt. Does not affect the negative prompt.

  • true: Default. Enables rewriting. Use this for more diverse image content; the model adds details.

  • false: Disables rewriting. Use this for tighter control over image details. For best results, optimize your prompts based on Text-to-image prompt guide.

View rewriting examples

Only asynchronous calls return the actual rewritten prompt.

Original prompt (orig_prompt): A sitting orange cat with a joyful expression, lively and adorable, highly realistic.

Actual prompt (actual_prompt): A sitting orange cat with soft, fluffy fur bathed in warm sunlight streaming through a window. Its body is proportionate, legs naturally bent, and it sits calmly on wooden floorboards. Its tail curls gently beside it, conveying relaxation and elegance. Its large, round eyes gleam with brightness and curiosity, its pupils slightly constricted, and its mouth hints at a joyful smile. Its ears tilt forward, showing liveliness and curiosity. The background is a cozy modern living room with light hardwood floors and a half-open window letting in soft natural light. Outside the window, a lush garden glows in the sunlight. Potted green plants sit on the windowsill. The image uses photorealistic style, with rich detail, layered lighting, and emphasis on the cat’s fur texture, facial expression, and natural posture. The overall mood is light, cheerful, and full of life.

watermark bool (optional)

Adds a “Qwen-Image” watermark to the bottom-right corner of the image. Default: false. Watermark style: 1

seed integer (optional)

Random number seed. Valid range: [0,2147483647].

Using the same seed yields similar outputs. If omitted, the algorithm uses a random seed.

Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

Task succeeded

Image URLs are valid for only 24 hours and then automatically purged. Save generated images promptly.

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": [
                        {
                            "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ],
                    "role": "assistant"
                }
            }
        ]
    },
    "usage": {
        "height": 2048,
        "image_count": 1,
        "width": 2048
    },
    "request_id": "d0250a3d-b07f-49e1-bdc8-6793f4929xxx"
}

Task failed

If the task fails, the response includes error details in the code and message fields. See Error codes.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

Task output information.

Properties

choices array

Model output. This array contains exactly one element.

Properties

finish_reason string

Reason the task stopped. Value is stop for natural stops.

message object

Model response message.

Properties

role string

Message role. Fixed value: assistant.

content array

Properties

image string

URL of the generated image (PNG format). Expires after 24 hours. Download and save it promptly.

task_metric object

Task result statistics. Not returned for qwen-image-2.0 series models.

Properties

TOTAL integer

Total number of tasks.

SUCCEEDED integer

Number of successful tasks.

FAILED integer

Number of failed tasks.

usage object

Output statistics. Counts only successful results.

Properties

image_count integer

Number of generated images. For qwen-image-2.0 series models this equals the requested n (1–6); for qwen-image-max and qwen-image-plus series it is fixed at 1.

width integer

Width of the generated image, in pixels.

height integer

Height of the generated image, in pixels.

request_id string

Unique request identifier for tracing and troubleshooting.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

DashScope SDK call

The DashScope SDK supports Python and Java.

The parameter names in the SDK closely match the HTTP parameters, and the parameter structures follow language-specific conventions. For synchronous call parameters, see HTTP.

Python

Note

Install the latest DashScope Python SDK to avoid runtime errors: Install SDK.

Request example
import json
import os
import dashscope
from dashscope import MultiModalConversation

# Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

messages = [
    {
        "role": "user",
        "content": [
            {"text": "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow."}
        ]
    }
]

# API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
# If you haven't set the environment variable, replace the line below with: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

response = MultiModalConversation.call(
    api_key=api_key,
    model="qwen-image-2.0-pro",
    messages=messages,
    result_format='message',
    stream=False,
    watermark=False,
    prompt_extend=True,
    negative_prompt="Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
    size='2048*2048'
)

if response.status_code == 200:
    print(json.dumps(response, ensure_ascii=False))
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("See documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code")
Response example
Image URLs expire after 24 hours. Download the images promptly.
{
    "status_code": 200,
    "request_id": "d2d1a8c0-325f-9b9d-8b90-xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "width": 2048,
        "image_count": 1,
        "height": 2048
    }
}

Java

Note

You must install the latest DashScope Java SDK. Otherwise, runtime errors may occur: Install SDK.

Request example
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class QwenImage {

    static {
        // Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
    }

    // API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
    // If you haven't set the environment variable, replace the line below with: static String apiKey ="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {

        MultiModalConversation conv = new MultiModalConversation();

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("text", "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow.")
                )).build();

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false);
        parameters.put("prompt_extend", true);
        parameters.put("negative_prompt", "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.");
        parameters.put("size", "2048*2048");

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(apiKey)
                .model("qwen-image-2.0-pro")
                .messages(Collections.singletonList(userMessage))
                .parameters(parameters)
                .build();

        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            call();
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
Response example
Image URLs expire after 24 hours. Download the images promptly.
{
    "requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
    "usage": {
        "image_count": 1,
        "width": 2048,
        "height": 2048
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
                        }
                    ]
                }
            }
        ]
    }
}

Asynchronous API

Important

Only qwen-image-plus and qwen-image support asynchronous calls.

HTTP

Asynchronous calls use a two-step HTTP workflow:

  1. Create a task to get a task ID: Send a request to create a task. The response returns a task ID (task_id).

  2. Poll for results using the task ID: Poll the task status with the task_id until it completes and returns an image URL.

Step 1: Create a task to get a task ID

Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Note
  • After the task is created, use the returned task_id to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result.

  • For guidance for beginners, see Call APIs with Postman or cURL.

Request parameters

Text-to-image

Only qwen-image-plus and qwen-image support asynchronous calls.

curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "qwen-image-plus",
    "input": {
        "prompt": "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower."
    },
    "parameters": {
        "negative_prompt":" ",
        "size": "1664*928",
        "n": 1,
        "prompt_extend": true,
        "watermark": false
    }
}'        

Request headers

Content-Type string (Required)

The content type of the request. Must be application/json.

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be enable.

Important

If this request header is missing, the error "current user api does not support synchronous calls" is returned.

Request body

model string (required)

Model name. Only qwen-image-plus and qwen-image support asynchronous calls.

Example: qwen-image-plus.

input object (required)

Input information.

Properties

prompt string (required)

A positive prompt describing the visual elements and characteristics you want in the generated image.

Supports Chinese and English. Maximum length is 800 characters. Each Chinese character, letter, digit, or symbol counts as one character. Excess characters are truncated automatically.

Example: A sitting orange cat with a joyful expression, lively and adorable, highly realistic.

negative_prompt string (optional)

A negative prompt describing what you do not want in the image.

Supports Chinese and English. Maximum length is 500 characters. Excess characters are truncated automatically.

Example: Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth surfaces, AI-generated look. Chaotic composition. Blurry or distorted text.

parameters object (optional)

Image processing parameters.

Properties

size string (optional)

Output image resolution, formatted as width*height.

qwen-image-2.0 series models: Total pixels must be between 512×512 and 2048×2048. Default resolution is 2048×2048. Recommended resolutions:

  • 2688*1536: 16:9

  • 1536*2688: 9:16

  • 2048*2048 (default): 1:1

  • 2368*1728: 4:3

  • 1728*2368: 3:4

qwen-image-max and qwen-image-plus series models: Default resolution is 1664*928. Supported resolutions and their aspect ratios:

  • 1664*928 (default): 16:9

  • 1472*1104: 4:3

  • 1328*1328: 1:1

  • 1104*1472: 3:4

  • 928*1664: 9:16

n integer (optional)

Number of generated images. This value is fixed at 1. Setting any other value returns an error.

prompt_extend bool (optional)

Enable smart prompt rewriting. The model optimizes the positive prompt. Does not affect the negative prompt.

  • true: Default. Enables rewriting. Use this for more diverse image content; the model adds details.

  • false: Disables rewriting. Use this for tighter control over image details. For best results, optimize your prompts based on Text-to-image prompt guide.

View rewriting examples

Only asynchronous calls return the actual rewritten prompt.

Original prompt (orig_prompt): A sitting orange cat with a joyful expression, lively and adorable, highly realistic.

Actual prompt (actual_prompt): A sitting orange cat with soft, fluffy fur bathed in warm sunlight streaming through a window. Its body is proportionate, legs naturally bent, and it sits calmly on wooden floorboards. Its tail curls gently beside it, conveying relaxation and elegance. Its large, round eyes gleam with brightness and curiosity, its pupils slightly constricted, and its mouth hints at a joyful smile. Its ears tilt forward, showing liveliness and curiosity. The background is a cozy modern living room with light hardwood floors and a half-open window letting in soft natural light. Outside the window, a lush garden glows in the sunlight. Potted green plants sit on the windowsill. The image uses photorealistic style, with rich detail, layered lighting, and emphasis on the cat’s fur texture, facial expression, and natural posture. The overall mood is light, cheerful, and full of life.

watermark bool (optional)

Adds a “Qwen-Image” watermark to the bottom-right corner of the image. Default: false. Watermark style: 1

seed integer (optional)

Random number seed. Valid range: [0,2147483647].

Using the same seed yields similar outputs. If omitted, the algorithm uses a random seed.

Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

Successful response

Save the task_id to query the task status and result.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Error response

Task creation failed. See Error codes.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

Task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: The task does not exist or its status is unknown.

request_id string

Unique request identifier for tracing and troubleshooting.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

Step 2: Poll for results using the task ID

China (Beijing)

GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

When calling, replace WorkspaceId with your actual workspace ID.

Note
  • Polling recommendation: Image generation is time-consuming. Use a polling mechanism with a reasonable interval, such as 10 seconds.

  • Task state transition: PENDING → RUNNING → SUCCEEDED or FAILED.

  • Result link: After a task succeeds, an image URL valid for 24 hours is returned. Download and save the image to permanent storage, such as OSS.

  • Requests Per Second (RPS) limit: The default RPS for the query API is 20. For higher-frequency queries or event notifications, we recommend that you configure an asynchronous task callback.

  • More operations: For batch queries, task cancellation, and other operations, see Manage asynchronous tasks.

Request parameters

Poll for task results

Replace {task_id} with the task_id value returned by the previous API call. The task_id is valid for queries for 24 hours.

curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Request headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

URL path parameters

task_id string (Required)

The ID of the task.

Response parameters

Task succeeded

Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

{
    "request_id": "cf4a3304-fa4d-97b6-bc72-xxxxxx",
    "output": {
        "task_id": "18e7cde0-8c17-42aa-afc5-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-09-05 11:33:20.542",
        "scheduled_time": "2025-09-05 11:33:20.581",
        "end_time": "2025-09-05 11:33:40.807",
        "results": [
            {
                "orig_prompt": "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.",
                "actual_prompt": "An elegant and solemn pair of Chinese couplets hangs in the center of a traditional Chinese hall. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” and the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” with the horizontal banner “Zhi Qi Qwen.” The calligraphy uses a flowing, expressive script with balanced ink tones, conveying deep cultural resonance and artistic elegance. Centered between the couplets is a traditional Chinese painting of Yueyang Tower—its upturned eaves rise beside water, distant mountains fade into misty clouds, and the whole scene evokes poetic tranquility.\n\nThe background is a serene, classically furnished Chinese room with antique wooden structures and soft lighting that creates a dignified, peaceful atmosphere. The couplets hang on the central wall above a long table displaying several blue-and-white porcelain pieces—vases and tea sets with refined shapes and delicate patterns, their blue-and-white glazes harmonizing perfectly with the setting. The overall style follows traditional Chinese ink wash aesthetics: smooth lines, subtle colors, and rich classical beauty.",
                "url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/7d/xxx.png?Expires=xxxx"
            }
        ]
    },
    "usage": {
        "image_count": 1
    }
}

Task failed

When a task fails, task_status is FAILED with an error code and message. See Error codes.

{
    "request_id": "c61fe158-c0de-40f0-b4d9-964625119ba4",
    "output": {
        "task_id": "86ecf553-d340-4e21-xxxxxxxxx",
        "task_status": "FAILED",
        "submit_time": "2025-11-11 11:46:28.116",
        "scheduled_time": "2025-11-11 11:46:28.154",
        "end_time": "2025-11-11 11:46:28.255",
        "code": "InvalidParameter",
        "message": "xxxxxxxx"
    }
}

output object

Task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: The task does not exist or its status is unknown.

submit_time string

The time when the task was submitted. format is YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The time when the task was executed. format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the task was completed. format is YYYY-MM-DD HH:mm:ss.SSS.

results array

List of task results, including image URLs, prompts, and error messages for failed tasks.

Properties

orig_prompt string

The original input prompt, corresponding to the request parameter prompt.

actual_prompt string

The optimized prompt used when prompt rewriting is enabled. Not returned when disabled.

url string

URL of the generated image. Expires after 24 hours. Download and save the image promptly.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

usage object

Output statistics. Counts only successful results.

Properties

image_count integer

Number of generated images. For qwen-image-2.0 series models this equals the requested n (1–6); for qwen-image-max and qwen-image-plus series it is fixed at 1.

request_id string

Unique request identifier for tracing and troubleshooting.

DashScope SDK

The DashScope SDK supports Python and Java.

SDK parameter names closely match their HTTP counterparts. Parameter structures follow language-specific conventions. For asynchronous call parameters, see HTTP.

Image models require longer processing times, so the underlying service uses asynchronous execution. The SDK provides two modes:

  • Synchronous call (blocking mode): The SDK waits for the task to complete and returns the final result. This matches standard synchronous call behavior.

  • Asynchronous call (non-blocking mode): The call returns immediately with a task ID. Poll for the task status and final result using that ID.

Python SDK

Note

Install the latest DashScope Python SDK to avoid runtime errors: Install SDK.

Synchronous

Request example
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope

# Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

prompt = "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower."

# API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
# If you haven't set the environment variable, replace the line below with: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

print('----Synchronous call, please wait for task to complete----')
rsp = ImageSynthesis.call(api_key=api_key,
                          model="qwen-image-plus", # Only qwen-image-plus and qwen-image support asynchronous calls
                          prompt=prompt,
                          negative_prompt=" ",
                          n=1,
                          size='1664*928',
                          prompt_extend=True,
                          watermark=False)
print(f'response: {rsp}')
if rsp.status_code == HTTPStatus.OK:
    # Save image in current directory
    for result in rsp.output.results:
        file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(result.url).content)
else:
    print(f'Synchronous call failed, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
Response example
URLs expire after 24 hours. Download images promptly.
{
    "status_code": 200,
    "request_id": "03b1ef03-480d-4ea5-ba52-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "3cefd9bc-fcb2-4de9-a8bc-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxxxx",
                "orig_prompt": "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.",
                "actual_prompt": "An elegant and solemn pair of Chinese couplets hangs in the center of a traditional Chinese hall. The space features a quiet, antique Chinese interior. The hall contains sturdy wooden furniture, walls finished with pale imitation antique paper texture, and dark wood flooring, creating a serene and dignified ambiance. The couplets use fluid calligraphy: the left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner reads “Zhi Qi Qwen.” The symmetrical layout, deep ink tones, and powerful brushwork convey profound cultural depth and philosophical insight.\n\nCentered between the couplets hangs a traditional Chinese painting of Yueyang Tower. The tower rises beside water, backed by the vast Dongting Lake, with distant hills fading into misty clouds. Rendered in classic ink wash technique, the painting features delicate strokes and a distant, poetic mood. Below the painting sits a redwood Chinese table displaying several blue-and-white porcelain items—including vases and tea sets—with clear glazes and elegant patterns that harmonize with the overall aesthetic. The entire composition follows classical Chinese ink wash style, with clear spatial layers and a tranquil, refined atmosphere that embodies rich Eastern cultural heritage."
            }
        ],
        "submit_time": "2025-09-09 13:41:54.041",
        "scheduled_time": "2025-09-09 13:41:54.087",
        "end_time": "2025-09-09 13:42:22.596"
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous

Request example
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
import time

# Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

prompt = "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower."

# If you haven't set the environment variable, replace the line below with: api_key="sk-xxx"
# API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

def async_call():
    print('----Create task----')
    task_info = create_async_task()
    print('----Poll task status----')
    poll_task_status(task_info)

# Create asynchronous task
def create_async_task():
    rsp = ImageSynthesis.async_call(api_key=api_key,
                                    model="qwen-image-plus", # Only qwen-image-plus and qwen-image support asynchronous calls
                                    prompt=prompt,
                                    negative_prompt=" ",
                                    n=1,
                                    size='1664*928',
                                    prompt_extend=True,
                                    watermark=False)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
    else:
        print(f'Failed to create task, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
    return rsp

# Poll asynchronous task status, query every 5 seconds, maximum polling for 1 minute
def poll_task_status(task):
    start_time = time.time()
    timeout = 60  # 1 minute timeout
    
    while True:
        # Check if timeout
        if time.time() - start_time > timeout:
            print('Polling timeout (1 minute), task not completed')
            return
            
        # Get task status
        status_rsp = ImageSynthesis.fetch(task)
        print(f'Task status query result: {status_rsp}')
        
        if status_rsp.status_code != HTTPStatus.OK:
            print(f'Failed to get task status, status_code: {status_rsp.status_code}, code: {status_rsp.code}, message: {status_rsp.message}')
            return
        task_status = status_rsp.output.task_status
        print(f'Current task status: {task_status}')
        
        if task_status == 'SUCCEEDED':
            print('Task completed, downloading image...')
            for result in status_rsp.output.results:
                file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
                with open(f'./{file_name}', 'wb+') as f:
                    f.write(requests.get(result.url).content)
                print(f'Image saved as: {file_name}')
            break
        elif task_status == 'FAILED':
            print(f'Task execution failed, status: {task_status}, code: {status_rsp.code}, message: {status_rsp.message}')
            break
        elif task_status == 'PENDING' or task_status == 'RUNNING':
            print('Task in progress, continue querying after 5 seconds...')
            time.sleep(5)
        else:
            print(f'Unknown task status: {task_status}, continue querying after 5 seconds...')
            time.sleep(5)

# Cancel asynchronous task, only tasks in PENDING status can be canceled
def cancel_task(task):
    rsp = ImageSynthesis.cancel(task)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output.task_status)
    else:
        print(f'Failed to cancel task, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')

if __name__ == '__main__':
    async_call()
Response example
  1. Response for task creation

    {
    	"status_code": 200,
    	"request_id": "31b04171-011c-96bd-ac00-xxxxxx",
    	"code": "",
    	"message": "",
    	"output": {
    		"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
    		"task_status": "PENDING",
    		"results": []
    	},
    	"usage": null
    }
  2. Response for polling task results

    URLs expire after 24 hours. Download images promptly.
    {
        "status_code": 200,
        "request_id": "03b1ef03-480d-4ea5-ba52-xxxxxx",
        "code": null,
        "message": "",
        "output": {
            "task_id": "3cefd9bc-fcb2-4de9-a8bc-xxxxxx",
            "task_status": "SUCCEEDED",
            "results": [
                {
                    "url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxxxx",
                    "orig_prompt": "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.",
                    "actual_prompt": "An elegant and solemn pair of Chinese couplets hangs in the center of a traditional Chinese hall. The space features a quiet, antique Chinese interior. The hall contains sturdy wooden furniture, walls finished with pale imitation antique paper texture, and dark wood flooring, creating a serene and dignified ambiance. The couplets use fluid calligraphy: the left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner reads “Zhi Qi Qwen.” The symmetrical layout, deep ink tones, and powerful brushwork convey profound cultural depth and philosophical insight.\n\nCentered between the couplets hangs a traditional Chinese painting of Yueyang Tower. The tower rises beside water, backed by the vast Dongting Lake, with distant hills fading into misty clouds. Rendered in classic ink wash technique, the painting features delicate strokes and a distant, poetic mood. Below the painting sits a redwood Chinese table displaying several blue-and-white porcelain items—including vases and tea sets—with clear glazes and elegant patterns that harmonize with the overall aesthetic. The entire composition follows classical Chinese ink wash style, with clear spatial layers and a tranquil, refined atmosphere that embodies rich Eastern cultural heritage."
                }
            ],
            "submit_time": "2025-09-09 13:41:54.041",
            "scheduled_time": "2025-09-09 13:41:54.087",
            "end_time": "2025-09-09 13:42:22.596"
        },
        "usage": {
            "image_count": 1
        }
    }
    

Java SDK

Note

You must install the latest DashScope Java SDK. Otherwise, runtime errors may occur: Install SDK.

Synchronous

Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;

public class Text2Image {
    static {
        // Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
    }

    // API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
    // If you haven't set the environment variable, replace the line below with: static String apiKey = "sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void basicCall() throws ApiException, NoApiKeyException {
        String prompt = "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("negative_prompt", " ");
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        // Only qwen-image-plus and qwen-image support asynchronous calls
                        .model("qwen-image-plus")
                        .prompt(prompt)
                        .n(1)
                        .size("1664*928")
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---Synchronous call, please wait for task to complete----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args){
        try{
            basicCall();
        }catch(ApiException|NoApiKeyException e){
            System.out.println(e.getMessage());
        }
    }
}
Response example
URLs expire after 24 hours. Download images promptly.
{
    "request_id": "f2153409-3950-9b73-9980-xxxxxx",
    "output": {
        "task_id": "2fc2e1de-0245-442d-b664-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "orig_prompt": "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.",
                "actual_prompt": "An elegant and solemn pair of Chinese couplets hangs in the center of a traditional Chinese hall. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner reads “Zhi Qi Qwen.” The calligraphy uses a flowing, expressive script with balanced ink tones, showcasing rich traditional charm. Between the couplets hangs a traditional Chinese painting of Yueyang Tower: the structure’s upturned eaves rise beside water, distant lake reflections shimmer, misty horizons stretch far, and wisps of cloud drift through the sky, creating a poetic atmosphere. The background room features a quiet, classical Chinese interior with smooth-lined wooden furniture and several blue-and-white porcelain pieces on the table—each with exquisite patterns and lustrous glazes. Soft ambient lighting enhances the dignified, tranquil cultural mood. The overall style follows traditional Chinese ink wash painting, with fine brushwork, clear layering, and classical beauty.",
                "url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
            }
        ]
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous

Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;

public class Text2Image {

    static {
        // Use this URL for Beijing region. For Singapore region, replace with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
    }

    // API keys differ between Beijing and Singapore regions. Get your API key: https://help.aliyun.com/en/model-studio/get-api-key
    // If you haven't set the environment variable, replace the line below with: static String apiKey = "sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public void asyncCall() {
        System.out.println("---Create task----");
        String taskId = this.createAsyncTask();
        System.out.println("--Wait for task to complete and return image URL----");
        this.waitAsyncTask(taskId);
    }

    public String createAsyncTask() {
        String prompt = "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("negative_prompt", " ");
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        // Only qwen-image-plus and qwen-image support asynchronous calls
                        .model("qwen-image-plus")
                        .prompt(prompt)
                        .n(1)
                        .size("1664*928")
                        .parameters(parameters)
                        .build();

        try {
            ImageSynthesisResult result = new ImageSynthesis().asyncCall(param);
            System.out.println(JsonUtils.toJson(result));
            String taskId = result.getOutput().getTaskId();
            System.out.println("task_id=" + taskId);
            return taskId;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        long startTime = System.currentTimeMillis();
        int timeout = 60 * 1000; // 1 minute timeout
        int interval = 5 * 1000;  // 5 second polling interval

        while (true) {
            if (System.currentTimeMillis() - startTime > timeout) {
                System.out.println("Polling timeout (1 minute), task not completed");
                return;
            }

            try {
                ImageSynthesisResult result = imageSynthesis.fetch(taskId, apiKey);
                System.out.println("Task status query result: " + JsonUtils.toJson(result));
                if (result.getOutput() == null) {
                    System.out.println("Failed to get task status, output is empty");
                    return;
                }
                String taskStatus = result.getOutput().getTaskStatus();
                System.out.println("Current task status: " + taskStatus);
                switch (taskStatus) {
                    case "SUCCEEDED":
                        System.out.println("Task completed");
                        System.out.println(JsonUtils.toJson(result));
                        return;
                    case "FAILED":
                        System.out.println("Task execution failed, status: " + taskStatus);
                        return;
                    case "PENDING":
                    case "RUNNING":
                        System.out.println("Task in progress, querying again in 5 seconds...");
                        Thread.sleep(interval);
                        break;
                    default:
                        System.out.println("Unknown task status: " + taskStatus + ", querying again in 5 seconds...");
                        Thread.sleep(interval);
                        break;
                }
            } catch (ApiException | NoApiKeyException e) {
                System.err.println("API call exception: " + e.getMessage());
                return;
            } catch (InterruptedException e) {
                System.err.println("Thread interruption exception: " + e.getMessage());
                Thread.currentThread().interrupt();
                return;
            }
        }
    }

    public static void main(String[] args){
        Text2Image text2Image = new Text2Image();
        text2Image.asyncCall();
    }
}
Response example
  1. Response for task creation

    {
    	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
    	"output": {
    		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
    		"task_status": "PENDING"
    	}
    }
  2. Response for polling task results

    URLs expire after 24 hours. Download images promptly.
    {
        "request_id": "f2153409-3950-9b73-9980-xxxxxx",
        "output": {
            "task_id": "2fc2e1de-0245-442d-b664-xxxxxx",
            "task_status": "SUCCEEDED",
            "results": [
                {
                    "orig_prompt": "An elegant and solemn pair of Chinese couplets hangs in a hall. The room features a quiet, classical Chinese interior with blue-and-white porcelain pieces on the table. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner above reads “Zhi Qi Qwen.” The calligraphy is fluid and graceful. In the center hangs a traditional Chinese painting depicting Yueyang Tower.",
                    "actual_prompt": "An elegant and solemn pair of Chinese couplets hangs in the center of a traditional Chinese hall. The left scroll reads “Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin,” the right scroll reads “Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan,” and the horizontal banner reads “Zhi Qi Qwen.” The calligraphy uses a flowing, expressive script with balanced ink tones, showcasing rich traditional charm. Between the couplets hangs a traditional Chinese painting of Yueyang Tower: the structure’s upturned eaves rise beside water, distant lake reflections shimmer, misty horizons stretch far, and wisps of cloud drift through the sky, creating a poetic atmosphere. The background room features a quiet, classical Chinese interior with smooth-lined wooden furniture and several blue-and-white porcelain pieces on the table—each with exquisite patterns and lustrous glazes. Soft ambient lighting enhances the dignified, tranquil cultural mood. The overall style follows traditional Chinese ink wash painting, with fine brushwork, clear layering, and classical beauty.",
                    "url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
                }
            ]
        },
        "usage": {
            "image_count": 1
        }
    }

Billing and rate limiting

Error codes

If the model call fails and returns an error message, see Error codes for resolution.

FAQ

Q: Should I enable or disable the prompt_extend parameter?

A: Enable this option (default) if you want more diverse image content and for the model to add details. Disable it if you need tighter control over image details, and optimize your prompts using the Text-to-Image Prompt Guide.

Q: What are the differences between qwen-image, qwen-image-plus, qwen-image-max, qwen-image-2.0, and qwen-image-edit?

A:

  • Combined image generation and editing models: Support both text-to-image and image editing.

    • qwen-image-2.0-pro and qwen-image-2.0-pro-2026-03-03: Same capabilities. The Pro series delivers more professional text rendering, finer realistic textures, detailed realistic scenes, and stronger semantic adherence. Supports synchronous calls only.

    • qwen-image-2.0 and qwen-image-2.0-2026-03-03: Same capabilities. The accelerated version balances model performance and quality. Supports synchronous calls only.

  • Text-to-image models: Generate images from text descriptions.

    • qwen-image-max and qwen-image-max-2025-12-30: Same capabilities. Compared with qwen-image-plus, they deliver improved realism and naturalness, with better results for character textures, details, and text rendering.

    • qwen-image and qwen-image-plus: Same capabilities, but qwen-image-plus is more cost-effective.

    • qwen-image-plus-2026-01-09: A new snapshot version of Qwen-Image. It is a distilled and accelerated version of qwen-image-max that supports fast generation of high-quality images.

  • Image editing model:qwen-image-edit: Performs image-to-image transformations, inpainting, and other operations based on an input image and text instructions. For more information, see Qwen - image editing.

Q: How do I get the domain name whitelist for image storage?

A: Images generated by models are stored in OSS. The API returns a temporary public URL. To configure a firewall whitelist for this download URL, note the following: The underlying storage may change dynamically. This topic does not provide a fixed OSS domain name whitelist to prevent access issues caused by outdated information. If you have security control requirements, contact your account manager to obtain the latest OSS domain name list.