All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan Image Generation and Editing 2.7 API Reference

Last Updated:Nov 20, 2026

The Wan2.7 image generation and editing models support text-to-image, text-to-image-set, image-to-image-set, image editing, and multi-image reference generation.

Model Overview

Model

Description

Output Image Specifications

wan2.7-image-pro

Wan2.7 image Pro supports 4K high-definition output for text-to-image (excluding image set generation)

Image format: PNG.

For image resolution and dimensions, see the size parameter.

wan2.7-image

Wan2.7 image, with faster generation speed

NoteBefore calling, check the model list and prices supported in each region.

Prerequisites

You must have obtained and configured an API Key and configured the API Key in environment variables. Replace DASHSCOPE_API_HOST in the sample code with the obtained API Host.

ImportantThe China (Beijing) and Singapore regions have separate API Keys and request endpoints, which cannot be mixed. Cross-region calls will cause authentication failures or service errors.

ImportantAlibaba Cloud Model Studio has launched workspace-dedicated domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:

  • China (Beijing) region: migrate from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: migrate from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

Here, {WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domains remain available.

HTTP synchronous call

Results are returned in a single request, with a simple workflow. It is recommended for most scenarios.

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.

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

When calling, replace {WorkspaceId} with your actual workspace ID.

Request parameters

Text-to-image

wan2.7-image-pro supports 4K resolution only in text-to-image scenarios; image editing and image set generation support up to 2K resolution

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"text": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false,
            "thinking_mode": true
        }
    }'

Image editing

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
                        {"text": "把图2的涂鸦喷绘在图1的汽车上"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'

Interactive editing

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"},
                        {"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"},
                        {"text": "把图1的闹钟放在图2的框选的位置,保持场景和光线融合自然"}
                    ]
                }
            ]
        },
        "parameters": {
            "bbox_list": [[],[[989, 515, 1138, 681]]],
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'

Group image generation

wan2.7-image-pro group image generation only supports resolutions up to 2K.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"text": "电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。"}
                    ]
                }
            ]
        },
        "parameters": {
            "enable_sequential": true,
            "n": 4,
            "size": "2K"
        }
    }'

Request Headers

Content-Typestring(Required)

Request content type. This parameter must be set to application/json.

Authorizationstring(Required)

Request authentication. The API uses an Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

Request Body

model string (Required)

Model. Valid values: wan2.7-image-pro, wan2.7-image.

input object (Required)

Basic input information.

property

messages array (Required)

Request content array. Currently, only single-round conversations are supported, that is, one set of role and content parameters is passed in; multi-round conversations are not supported.

property

role string (Required)

The role of the message. This parameter is fixed to user.

content array (Required)

Message content array.

property

text string

The prompt entered by the user. Both Chinese and English are supported, with a maximum length of 5,000 characters. Each Chinese character, letter, digit, or symbol counts as one character, and any part exceeding the limit is automatically truncated.

image string

The URL or Base64-encoded string of the input image.

Image limits:

  • Image formats: JPEG, JPG, PNG (transparent channel not supported), BMP, WEBP.
  • Image resolution: both the width and height of the image are in the range of [240, 8000] pixels, and the aspect ratio is in the range of [1:8, 8:1].
  • File size: no more than 20 MB.

Image quantity limits:

  • You can pass in 0 to 9 images.
  • When multiple images are input, you need to pass multiple image objects in the content array, and define the image order according to the array order.

Supported input formats:

  1. Use a publicly accessible URL

    • HTTP or HTTPS protocols are supported.
    • Example value: http://wanx.alicdn.com/material/xxx.jpeg.
  2. Pass in a Base64-encoded image string

    • Format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (for illustration only; you must pass the complete string in practice)
    • For the Base64 encoding specifications, see Image input methods.

parameters object (Optional)

Model parameter configuration.

property

bbox_list array[array[array[integer]]] (Optional)

Bounding box regions for interactive editing.

  • Correspondence: The list length must match the number of input images. If an image does not need editing, pass an empty list [] at the corresponding position.
  • Coordinate format: [x1, y1, x2, y2] (top-left x, top-left y, bottom-right x, bottom-right y), using absolute pixel coordinates of the original image, with the top-left corner at (0, 0).
  • Constraints: A maximum of 2 bounding boxes are supported per image.

Example: 3 images are input, where the 2nd has no bounding box and the 1st has two:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # 图 1 (2个框)
  [],                                    # 图 2 (无框)
  [[10, 10, 50, 50]]                    # 图 3 (1个框)
]

enable_sequential boolean (Optional)

Controls the image generation mode:

  • false: Default value.
  • true: Enables group image output mode.

size string (Optional)

Parameter for the output image resolution. Two methods are supported and cannot be mixed:

Model: wan2.7-image-pro
  • Method 1: Specify the output image resolution (recommended)
    • 1K, 2K (default), and 4K are supported

    • Applicable scope:

      • Text-to-image (no image input, non-group image generation): 1K, 2K, and 4K are supported.
      • Other scenarios: 1K and 2K are supported.
    • Total pixels per specification: 1K: 10241024, 2K: 20482048, 4K: 4096*4096

    • Aspect ratio:

      • When images are input: The output aspect ratio matches the input image (the last one for multi-image input) and is scaled to the selected resolution.
      • When no image is input: The output is a square.
  • Method 2: Specify the width and height pixel values of the generated image
    • Text-to-image: Total pixels range from [768768, 40964096], and the aspect ratio range is [1:8, 8:1].
    • Other scenarios: Total pixels range from [768768, 20482048], and the aspect ratio range is [1:8, 8:1].
Model: wan2.7-image
  • Method 1: Specify the output image resolution (recommended)
    • 1K and 2K (default) specifications are supported; 4K is not supported.
  • Method 2: Specify the width and height pixel values of the generated image
    • In all scenarios, total pixels range from [768768, 20482048], and the aspect ratio range is [1:8, 8:1].

The pixel values of the output image may differ slightly from the specified pixel values.

n integer (Optional)

Importantn directly affects the fee. Fee = Unit price × number of successfully generated images. Check the model pricing before calling.

  • When group image mode is disabled, this value represents the number of images to generate, with a range of 1-4 and a default of 1;
  • When group image mode is enabled, this value represents the maximum number of images to generate, with a range of 1-12 and a default of 12. The actual number is determined by the model and does not exceed n.

thinking_mode boolean (Optional)

Whether to enable thinking mode. The default is true (enabled). Only effective when group image mode is disabled and no image is input. When enabled, the model enhances its reasoning capability to improve image quality, but generation takes longer.

color_palette array (Optional)

Custom color theme. An array of objects containing color (hex) and ratio, which must include 3 to 10 colors, with 8 recommended.

Only available when group image mode is disabled (enable_sequential=false).

property

hex string (Required)

Color value in hexadecimal (HEX) format.

ratio string (required)

The percentage occupied by the color, accurate to two decimal places (for example, "25.00%"). The sum of all ratio values must equal 100.00%.

Click to view input examples

"color_palette": [
    {
        "hex": "#C2D1E6",
        "ratio": "23.51%"
    },
    {
        "hex": "#CDD8E9",
        "ratio": "20.13%"
    },
    {
        "hex": "#B5C8DB",
        "ratio": "15.88%"
    },
    {
        "hex": "#C0B5B4",
        "ratio": "13.27%"
    },
    {
        "hex": "#DAE0EC",
        "ratio": "10.11%"
    },
    {
        "hex": "#636574",
        "ratio": "8.93%"
    },
    {
        "hex": "#CACAD2",
        "ratio": "5.55%"
    },
    {
        "hex": "#CBD4E4",
        "ratio": "2.62%"
    }
]

watermark bool (optional)

Whether to add a watermark identifier. The watermark appears in the lower-right corner of the image, with the fixed text "AI-generated".

  • false: Default value. No watermark is added.
  • true: A watermark is added.

seed integer (optional)

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

Using the same seed parameter value keeps the generated content relatively stable. If not provided, the algorithm automatically uses a random number seed.

Note: The model generation process is probabilistic. Even with the same seed, identical results are not guaranteed for each generation.

Response parameters

Task executed successfully

Task data (such as task status and image URLs) is retained for only 24 hours and is automatically deleted after it expires. Be sure to save the generated images in a timely manner.

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": [
                        {
                            "image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ],
                    "role": "assistant"
                }
            }
        ],
        "finished": true
    },
    "usage": {
        "image_count": 1,
        "input_tokens": 10867,
        "output_tokens": 2,
        "size": "1488*704",
        "total_tokens": 10869
    },
    "request_id": "71dfc3c6-f796-9972-97e4-bc4efc4faxxx"
}

Task execution exception

If the task fails for some reason, related information is returned, and the cause of the error is clearly indicated by the code and message fields. See Error codes for troubleshooting.

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

output object

Task output information.

property

choices array

The output content generated by the model.

property

finish_reason string

The reason the task stopped. It is stop when the task stops naturally.

message object

The message returned by the model.

property

rolestring

The role of the message, fixed as assistant.

contentarray

property

type string

The type of the output, fixed as image.

image string

The URL of the generated image. The image format is PNG.

The link is valid for 24 hours. Download and save the image in a timely manner.

finished boolean

Whether the task has ended.

  • true: Ended.
  • false: Not ended.

usage object

Output information statistics. Only successful results are counted.

property

image_count integer

The number of generated images.

size string

The resolution of the generated image. Example value: 1376*768.

input_tokens integer

The number of input tokens (not billed). Billing is based on the number of images.

output_tokens integer

The number of output tokens (not billed). Billing is based on the number of images.

total_tokensinteger

The total number of tokens (not billed). Billing is based on the number of images.

request_idstring

The unique identifier of the request. It can be used for tracing request details and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

HTTP asynchronous call

Suitable for time-consuming tasks. It supports querying task status and results.

Step 1: Create a task to obtain the task ID

Singapore

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

When calling, replace {WorkspaceId} with your actual workspace ID.

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

When calling, replace {WorkspaceId} with your actual workspace ID.

Request parameters

Text-to-image

wan2.7-image-pro supports 4K resolution only in text-to-image scenarios; image editing and image set generation support up to 2K resolution

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header "X-DashScope-Async: enable" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"text": "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false,
            "thinking_mode": true
        }
    }'

Image editing

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header "X-DashScope-Async: enable" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
                        {"text": "把图2的涂鸦喷绘在图1的汽车上"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'

Interactive editing

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header "X-DashScope-Async: enable" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"},
                        {"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"},
                        {"text": "把图1的闹钟放在图2的框选的位置,保持场景和光线融合自然"}
                    ]
                }
            ]
        },
        "parameters": {
            "bbox_list": [[],[[989, 515, 1138, 681]]],
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'

Group image generation

wan2.7-image-pro group image generation only supports resolutions up to 2K.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header "X-DashScope-Async: enable" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"text": "电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。"}
                    ]
                }
            ]
        },
        "parameters": {
            "enable_sequential": true,
            "n": 4,
            "size": "2K"
        }
    }'

Request Headers

Content-Typestring(Required)

Request content type. This parameter must be set to application/json.

Authorizationstring(Required)

Request authentication. The API uses an Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

X-DashScope-Asyncstring(Required)

Asynchronous processing configuration parameter. HTTP requests only support asynchronous processing, so this parameter must be set to enable.

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

Request Body

model string (Required)

Model. Valid values: wan2.7-image-pro, wan2.7-image.

input object (Required)

Basic input information.

property

messages array (Required)

Request content array. Currently, only single-round conversations are supported, that is, one set of role and content parameters is passed in; multi-round conversations are not supported.

property

role string (Required)

The role of the message. This parameter is fixed to user.

content array (Required)

Message content array.

property

text string

The prompt entered by the user. Both Chinese and English are supported, with a maximum length of 5,000 characters. Each Chinese character, letter, digit, or symbol counts as one character, and any part exceeding the limit is automatically truncated.

image string

The URL or Base64-encoded string of the input image.

Image limits:

  • Image formats: JPEG, JPG, PNG (transparent channel not supported), BMP, WEBP.
  • Image resolution: both the width and height of the image are in the range of [240, 8000] pixels, and the aspect ratio is in the range of [1:8, 8:1].
  • File size: no more than 20 MB.

Image quantity limits:

  • You can pass in 0 to 9 images.
  • When multiple images are input, you need to pass multiple image objects in the content array, and define the image order according to the array order.

Supported input formats:

  1. Use a publicly accessible URL

    • HTTP or HTTPS protocols are supported.
    • Example value: http://wanx.alicdn.com/material/xxx.jpeg.
  2. Pass in a Base64-encoded image string

    • Format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (for illustration only; you must pass the complete string in practice)
    • For the Base64 encoding specifications, see Image input methods.

parameters object (Optional)

Model parameter configuration.

property

bbox_list array[array[array[integer]]] (Optional)

Bounding box regions for interactive editing.

  • Correspondence: The list length must match the number of input images. If an image does not need editing, pass an empty list [] at the corresponding position.
  • Coordinate format: [x1, y1, x2, y2] (top-left x, top-left y, bottom-right x, bottom-right y), using absolute pixel coordinates of the original image, with the top-left corner at (0, 0).
  • Constraints: A maximum of 2 bounding boxes are supported per image.

Example: 3 images are input, where the 2nd has no bounding box and the 1st has two:

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # 图 1 (2个框)
  [],                                    # 图 2 (无框)
  [[10, 10, 50, 50]]                    # 图 3 (1个框)
]

enable_sequential boolean (Optional)

Controls the image generation mode:

  • false: Default value.
  • true: Enables group image output mode.

size string (Optional)

Parameter for the output image resolution. Two methods are supported and cannot be mixed:

Model: wan2.7-image-pro
  • Method 1: Specify the output image resolution (recommended)
    • 1K, 2K (default), and 4K are supported

    • Applicable scope:

      • Text-to-image (no image input, non-group image generation): 1K, 2K, and 4K are supported.
      • Other scenarios: 1K and 2K are supported.
    • Total pixels per specification: 1K: 10241024, 2K: 20482048, 4K: 4096*4096

    • Aspect ratio:

      • When images are input: The output aspect ratio matches the input image (the last one for multi-image input) and is scaled to the selected resolution.
      • When no image is input: The output is a square.
  • Method 2: Specify the width and height pixel values of the generated image
    • Text-to-image: Total pixels range from [768768, 40964096], and the aspect ratio range is [1:8, 8:1].
    • Other scenarios: Total pixels range from [768768, 20482048], and the aspect ratio range is [1:8, 8:1].
Model: wan2.7-image
  • Method 1: Specify the output image resolution (recommended)
    • 1K and 2K (default) specifications are supported; 4K is not supported.
  • Method 2: Specify the width and height pixel values of the generated image
    • In all scenarios, total pixels range from [768768, 20482048], and the aspect ratio range is [1:8, 8:1].

The pixel values of the output image may differ slightly from the specified pixel values.

n integer (Optional)

Importantn directly affects the fee. Fee = Unit price × number of successfully generated images. Check the model pricing before calling.

  • When group image mode is disabled, this value represents the number of images to generate, with a range of 1-4 and a default of 1;
  • When group image mode is enabled, this value represents the maximum number of images to generate, with a range of 1-12 and a default of 12. The actual number is determined by the model and does not exceed n.

thinking_mode boolean (Optional)

Whether to enable thinking mode. The default is true (enabled). Only effective when group image mode is disabled and no image is input. When enabled, the model enhances its reasoning capability to improve image quality, but generation takes longer.

color_palette array (Optional)

Custom color theme. An array of objects containing color (hex) and ratio, which must include 3 to 10 colors, with 8 recommended.

Only available when group image mode is disabled (enable_sequential=false).

property

hex string (Required)

Color value in hexadecimal (HEX) format.

ratio string (required)

The percentage occupied by the color, accurate to two decimal places (for example, "25.00%"). The sum of all ratio values must equal 100.00%.

Click to view input examples

"color_palette": [
    {
        "hex": "#C2D1E6",
        "ratio": "23.51%"
    },
    {
        "hex": "#CDD8E9",
        "ratio": "20.13%"
    },
    {
        "hex": "#B5C8DB",
        "ratio": "15.88%"
    },
    {
        "hex": "#C0B5B4",
        "ratio": "13.27%"
    },
    {
        "hex": "#DAE0EC",
        "ratio": "10.11%"
    },
    {
        "hex": "#636574",
        "ratio": "8.93%"
    },
    {
        "hex": "#CACAD2",
        "ratio": "5.55%"
    },
    {
        "hex": "#CBD4E4",
        "ratio": "2.62%"
    }
]

watermark bool (optional)

Whether to add a watermark identifier. The watermark appears in the lower-right corner of the image, with the fixed text "AI-generated".

  • false: Default value. No watermark is added.
  • true: A watermark is added.

seed integer (optional)

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

Using the same seed parameter value keeps the generated content relatively stable. If not provided, the algorithm automatically uses a random number seed.

Note: The model generation process is probabilistic. Even with the same seed, identical results are not guaranteed for each generation.

Response parameters

Success response

Save the task_id, which is used to query the task status and results.

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

Error response

If the task fails to be created, see Error codes for troubleshooting.

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

output object

Task output information.

property

task_id string

The task ID. The validity period for queries is 24 hours.

task_status string

The task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is processing
  • SUCCEEDED: The task executed successfully
  • FAILED: The task execution failed
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or the status is unknown

request_idstring

The unique identifier of the request. It can be used for tracing request details and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

Step 2: Query the result by task ID

Singapore

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

Beijing

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

Request parameters

Query task results

Replace {task_id} with the value of task_id returned by the API in the previous step. task_id is valid for queries for 24 hours. Replace {WorkspaceId} with the actual Workspace ID.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Request Headers

Authorizationstring(Required)

Request authentication. The API uses an Alibaba Cloud Model Studio API Key for authentication. Example value: Bearer sk-xxxx.

URL Path Parameters

task_id string(Required)

The node ID.

Response parameters

Task executed successfully

Task data (such as task status and image URLs) is retained for only 24 hours and is automatically deleted after it expires. Be sure to save the generated images in a timely manner.

{
    "request_id": "810fa5f5-334c-91f3-aaa4-ed89cf0caxxx",
    "output": {
        "task_id": "a81ee7cb-014c-473d-b842-76e98311cxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-03-26 17:16:01.663",
        "scheduled_time": "2026-03-26 17:16:01.716",
        "end_time": "2026-03-26 17:16:22.961",
        "finished": true,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "size": "2976*1408",
        "total_tokens": 11017,
        "image_count": 1,
        "output_tokens": 2,
        "input_tokens": 11015
    }
}

Task execution exception

If the task fails for some reason, related information is returned, and the cause of the error is clearly indicated by the code and message fields. See Error codes for troubleshooting.

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

output object

Task output information.

property

task_id string

The task ID. The validity period for queries is 24 hours.

task_status string

The task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is processing
  • SUCCEEDED: The task executed successfully
  • FAILED: The task execution failed
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or the status is unknown
Status transitions during polling:
  • PENDING (Queuing) → RUNNING (Processing) → SUCCEEDED (Success) / FAILED (Failed).
  • The status returned by the first query is usually PENDING (Queuing) or RUNNING (Processing).
  • When the status changes to SUCCEEDED, the response will contain the URL of the generated image.
  • If the status is FAILED, check the error message and try again.

submit_time string

The time when the node was submitted. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The node execution time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the node was completed. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.

finished boolean

Whether the task has ended.

  • true: Ended.
  • false: Not ended.

choices array

The output content generated by the model.

property

finish_reason string

The reason the node stopped; stop when it stops naturally.

message object

The message returned by the model.

property

rolestring

The role of the message, fixed as assistant.

contentarray

property

type string

The type of the output. Enumerated values: text and image.

text string

The generated text.

image string

The URL of the generated image. The image format is PNG.

The link is valid for 24 hours. Download and save the image in a timely manner.

usage object

Output information statistics. Only successful results are counted.

property

image_count integer

The number of generated images.

size string

The resolution of the generated image. Example value: 1376*768.

input_tokens integer

The number of input tokens (not billed). Billing is based on the number of images.

output_tokens integer

The number of output tokens (not billed). Billing is based on the number of images.

total_tokensinteger

The total number of tokens (not billed). Billing is based on the number of images.

request_idstring

The unique identifier of the request. It can be used for tracing request details and troubleshooting.

codestring

The error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

messagestring

The detailed error information returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.

Python SDK calls

SDK parameter naming is basically the same as that of the HTTP API.

Nodes may take a long time. The SDK has encapsulated the HTTP asynchronous call process and supports both synchronous and asynchronous calls.

The actual duration depends on the number of queued nodes and service execution. Please wait patiently when obtaining the results.

ImportantMake sure the DashScope Python SDK version is no earlier than 2.1.0 before running the following code. For updates, see Install SDK.

The base_url and API Key of each region are not interchangeable. The following examples use the Singapore region as an example:

Singapore

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

When calling, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When calling, replace {WorkspaceId} with your actual Workspace ID.

Image editing

Synchronous call

Request example
import os
import base64
import mimetypes
import urllib.request
import dashscope

# 以下为新加坡地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# --- Base64编码函数 ---
# base64编码格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("不支持或无法识别的图像格式")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
图像输入方式说明:
以下提供了三种图片输入方式,三选一即可
1. 使用公网URL - 适合已有公开可访问的图片
2. 使用本地文件 - 适合本地开发测试
3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
"""
# 【方式一】使用公网图片 URL
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# 【方式三】使用Base64编码的图片
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

print("----sync call, please wait a moment----")
# generate 为一步式调用(提交+等待),直接返回已完成的任务结果
job = client.images.generate(
    model="wan2.7-image-pro",
    prompt="把图2的涂鸦喷绘在图1的汽车上",
    # 参考图列表,支持本地文件 如 "file:///path/to/your/car.png"
    image_urls=[image_1, image_2],
    watermark=False,
    n=1,
    size="2K",  # wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
)

# 提取结果图片URL并保存到本地
for i, image_url in enumerate(job.image_urls):
    file_name = f"output_{i}.png"
    # 结果URL有效期为24小时,请及时下载
    urllib.request.urlretrieve(image_url, file_name)
    print(f"Image saved to {file_name}")
Response example

The URL is valid for 24 hours. Download the image promptly.

{
    "status_code": 200,
    "request_id": "81d868c6-6ce1-92d8-a90d-d2ee71xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "finished": true
    },
    "usage": {
        "input_tokens": 18790,
        "output_tokens": 2,
        "characters": 0,
        "image_count": 1,
        "size": "2985*1405",
        "total_tokens": 18792
    }
}

Asynchronous call

Request example
import os
import base64
import mimetypes
import urllib.request
import dashscope

# 以下为新加坡地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# --- Base64编码函数 ---
# base64编码格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("不支持或无法识别的图像格式")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
图像输入方式说明:
以下提供了三种图片输入方式,三选一即可
1. 使用公网URL - 适合已有公开可访问的图片
2. 使用本地文件 - 适合本地开发测试
3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
"""
# 【方式一】使用公网图片 URL
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# 【方式三】使用Base64编码的图片
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

# 创建异步任务
def create_async_task():
    print("Creating async task...")
    job = client.images.jobs.create(
        model="wan2.7-image-pro",
        prompt="把图2的涂鸦喷绘在图1的汽车上",
        extra_input={'images': [image_1, image_2]},
        watermark=False,
        n=1,
        size="2K",  # wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
    )

    print("Task created successfully:", job.task_id, job.status)
    return job

# 等待任务完成(指数退避轮询,默认总预算24小时;任务失败会抛出DashScopeError)
def wait_for_completion(job):
    print("Waiting for task completion...")
    done = client.images.jobs.wait(job)

    print("Task succeeded!")
    # 提取结果图片URL并保存到本地
    for i, image_url in enumerate(done.image_urls):
        file_name = f"output_{i}.png"
        # 结果URL有效期为24小时,请及时下载
        urllib.request.urlretrieve(image_url, file_name)
        print(f"Image saved to {file_name}")

# 获取异步任务信息
def fetch_task_status(task_id):
    print("Fetching task status...")
    snapshot = client.images.jobs.fetch(task_id)

    print("Task status:", snapshot.status)

# 取消异步任务,只有处于PENDING状态的任务才可以取消
def cancel_task(task_id):
    print("Canceling task...")
    client.images.jobs.cancel(task_id)

# 主执行流程
if __name__ == "__main__":
    job = create_async_task()
    wait_for_completion(job)
Response example
  1. Response example of creating a node
{
    "status_code": 200,
    "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": null,
        "audio": null,
        "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
        "task_status": "PENDING"
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0
    }
}
  1. Response example of querying the node result

The URL is valid for 24 hours. Download the image promptly.

{
    "status_code": 200,
    "request_id": "3b99aae5-d26f-9059-8dd0-ee9ca4804xxx",
    "code": null,
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-03-31 22:58:47.646",
        "scheduled_time": "2026-03-31 22:58:47.683",
        "end_time": "2026-03-31 22:58:59.642",
        "finished": true
    },
    "usage": {
        "input_tokens": 18711,
        "output_tokens": 2,
        "characters": 0,
        "size": "2985*1405",
        "total_tokens": 18713,
        "image_count": 1
    }
}

Sequential image generation

Synchronous call

Request example
import os
import base64
import mimetypes
import urllib.request
import dashscope

# 以下为新加坡地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# --- Base64编码函数 ---
# base64编码格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("不支持或无法识别的图像格式")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
图像输入方式说明(图生组图场景):
以下提供了三种图片输入方式,三选一即可
1. 使用公网URL - 适合已有公开可访问的图片
2. 使用本地文件 - 适合本地开发测试
3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
"""
# 【方式一】使用公网图片 URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# image_1 = "file:///path/to/your/image.png"

# 【方式三】使用Base64编码的图片
# image_1 = encode_file("/path/to/your/image.png")

print("----sync call, please wait a moment----")
# generate 为一步式调用(提交+等待),直接返回已完成的任务结果
job = client.images.generate(
    model="wan2.7-image-pro",
    prompt="电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。",
    # 图生组图场景:取消以下注释,传入参考图(并将上方提示词改为参考图片风格生成四季组图)
    # image_urls=[image_1],
    parameters={"enable_sequential": True},  # 组图生成
    n=4,
    size="2K",  # wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
)

# 提取结果图片URL并保存到本地
for i, image_url in enumerate(job.image_urls):
    file_name = f"output_{i}.png"
    # 结果URL有效期为24小时,请及时下载
    urllib.request.urlretrieve(image_url, file_name)
    print(f"Image saved to {file_name}")
Response example

The URL is valid for 24 hours. Download the image promptly.

{
    "status_code": 200,
    "request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "finished": true
    },
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "characters": 0,
        "image_count": 4,
        "size": "2048*2048",
        "total_tokens": 731
    }
}

Asynchronous call

Request example
import os
import base64
import mimetypes
import urllib.request
import dashscope

# 以下为新加坡地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# --- Base64编码函数 ---
# base64编码格式为 data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("不支持或无法识别的图像格式")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return f"data:{mime_type};base64,{encoded_string}"

"""
图像输入方式说明(图生组图场景):
以下提供了三种图片输入方式,三选一即可
1. 使用公网URL - 适合已有公开可访问的图片
2. 使用本地文件 - 适合本地开发测试
3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
"""
# 【方式一】使用公网图片 URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# image_1 = "file:///path/to/your/image.png"

# 【方式三】使用Base64编码的图片
# image_1 = encode_file("/path/to/your/image.png")

def main():
    # 提交异步任务
    print("提交异步任务...")
    job = client.images.jobs.create(
        model="wan2.7-image-pro",
        prompt="电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。",
        # 图生组图场景:取消以下注释,传入参考图(并将上方提示词改为参考图片风格生成四季组图)
        # extra_input={'images': [image_1]},
        parameters={"enable_sequential": True},  # 组图生成
        n=4,
        size="2K",  # wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
    )
    print(f"任务提交成功,任务ID: {job.task_id}")

    # 等待任务完成(指数退避轮询,默认总预算24小时;任务失败会抛出DashScopeError)
    done = client.images.jobs.wait(job)

    if done.succeeded:
        print("任务完成!")
        # 提取结果图片URL并保存到本地
        for i, image_url in enumerate(done.image_urls):
            file_name = f"output_{i}.png"
            # 结果URL有效期为24小时,请及时下载
            urllib.request.urlretrieve(image_url, file_name)
            print(f"Image saved to {file_name}")
    else:
        print(f"任务失败,状态: {done.status}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"错误: {e}")
Response example
  1. Response example of creating a node
{
    "status_code": 200,
    "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": null,
        "audio": null,
        "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
        "task_status": "PENDING"
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 0
    }
}
  1. Response example of querying the node result

The URL is valid for 24 hours. Download the image promptly.

{
    "status_code": 200,
    "request_id": "56e318fd-ed60-99e8-8ca1-cdef25ca4xxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "task_id": "77093787-a217-4c29-9cd4-ca7b5ac86xxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-03-31 23:04:46.166",
        "scheduled_time": "2026-03-31 23:04:46.208",
        "end_time": "2026-03-31 23:05:11.664",
        "finished": true
    },
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "characters": 0,
        "size": "2048*2048",
        "total_tokens": 731,
        "image_count": 4
    }
}

Java SDK calls

SDK parameter naming is basically the same as that of the HTTP API.

Nodes may take a long time. The SDK has encapsulated the HTTP asynchronous call process and supports both synchronous and asynchronous calls.

ImportantMake sure that the DashScope Java SDK version is 2.22.13 or later; otherwise, some parameters used in this topic may not be supported.

Singapore

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

When calling, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When calling, replace {WorkspaceId} with your actual Workspace ID.

Image editing

Synchronous call

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
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.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro 图像编辑 - 同步调用示例
 */
public class Main {

    static {
        // 以下为新加坡地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64编码函数 ---
    // base64编码格式为 data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 图像输入方式说明:
         * 以下提供了三种图片输入方式,三选一即可
         * 1. 使用公网URL - 适合已有公开可访问的图片
         * 2. 使用本地文件 - 适合本地开发测试
         * 3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
         */
        // 【方式一】使用公网图片 URL
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // 【方式二】使用本地文件(支持绝对路径和相对路径)
        // 格式要求:file:// + 文件路径
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // 【方式三】使用Base64编码的图片
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // 构建多图输入消息
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // 支持多图输入,可以提供多张参考图片
                        Collections.singletonMap("text", "把图2的涂鸦喷绘在图1的汽车上"),
                        Collections.singletonMap("image", image1),
                        Collections.singletonMap("image", image2)
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .n(1)
                .size("2K") // wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---sync call for image editing, please wait a moment----");
            result = imageGeneration.call(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        // 提取结果图片URL并保存到本地
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // 结果URL有效期为24小时,请及时下载
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}
Response example

The URL is valid for 24 hours. Download and save the images in a timely manner.

{
    "requestId": "1bf6173a-e8de-9f75-94d3-5e618f875xxx",
    "usage": {
        "input_tokens": 18790,
        "output_tokens": 2,
        "total_tokens": 18792,
        "image_count": 1,
        "size": "2985*1405"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Asynchronous call

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
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.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro 图像编辑 - 异步调用示例
 */
public class Main {

    static {
        // 以下为新加坡地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64编码函数 ---
    // base64编码格式为 data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 图像输入方式说明:
         * 以下提供了三种图片输入方式,三选一即可
         * 1. 使用公网URL - 适合已有公开可访问的图片
         * 2. 使用本地文件 - 适合本地开发测试
         * 3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
         */
        // 【方式一】使用公网图片 URL
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // 【方式二】使用本地文件(支持绝对路径和相对路径)
        // 格式要求:file:// + 文件路径
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // 【方式三】使用Base64编码的图片
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // 构建多图输入消息
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // 支持多图输入,可以提供多张参考图片
                        Collections.singletonMap("text", "把图2的涂鸦喷绘在图1的汽车上"),
                        Collections.singletonMap("image", image1),
                        Collections.singletonMap("image", image2)
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .n(1)
                .size("2K") // wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
                .messages(Arrays.asList(message))
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---async call for image editing, creating task----");
            result = imageGeneration.asyncCall(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("任务创建结果:");
        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();
        // 等待任务完成
        waitTask(taskId);
    }

    public static void waitTask(String taskId) throws ApiException, NoApiKeyException, IOException {
        ImageGeneration imageGeneration = new ImageGeneration();
        System.out.println("\n---waiting for task completion----");
        ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
        // 提取结果图片URL并保存到本地
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // 结果URL有效期为24小时,请及时下载
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Response example
  1. Response example of creating a node
{
    "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
    "output": {
        "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
        "task_status": "PENDING"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}
  1. Response example of querying the node result

The URL is valid for 24 hours. Download and save the images in a timely manner.

{
    "requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx",
    "usage": {
        "input_tokens": 18711,
        "output_tokens": 2,
        "total_tokens": 18713,
        "image_count": 1,
        "size": "2985*1405"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
        "task_status": "SUCCEEDED",
        "finished": true,
        "submit_time": "2026-03-31 19:57:58.840",
        "scheduled_time": "2026-03-31 19:57:58.877",
        "end_time": "2026-03-31 19:58:11.563"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Sequential image generation

Synchronous call

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
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.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro 组图生成 - 同步调用示例(新加坡地域)
 */
public class Main {

    static {
        // 以下为新加坡地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64编码函数 ---
    // base64编码格式为 data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 图像输入方式说明(图生组图场景):
         * 以下提供了三种图片输入方式,三选一即可
         * 1. 使用公网URL - 适合已有公开可访问的图片
         * 2. 使用本地文件 - 适合本地开发测试
         * 3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
         */
        // 【方式一】使用公网图片 URL
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // 【方式二】使用本地文件(支持绝对路径和相对路径)
        // 格式要求:file:// + 文件路径
        // String image1 = "file:///path/to/your/image.png";

        // 【方式三】使用Base64编码的图片
        // String image1 = encodeFile("/path/to/your/image.png");

        // 构建文本输入消息(支持文生组图以及图生组图,此处以文生组图为例)
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。")
                )).build();
        // 图生组图场景:取消以下注释并注释掉上方纯文本构建
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "参考图片风格生成四季组图"),
        //                 Collections.singletonMap("image", image1)
        //         )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(true)
                .n(4)
                .size("2K") // wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("----sync call, please wait a moment----");
            result = imageGeneration.call(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        // 提取结果图片URL并保存到本地
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // 结果URL有效期为24小时,请及时下载
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}
Response example

The URL is valid for 24 hours. Download and save the images in a timely manner.

{
    "requestId": "4678c314-b37a-91c9-a2ae-2d3cd54bbxxx",
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "total_tokens": 731,
        "image_count": 4,
        "size": "2048*2048"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Asynchronous call

Request example
import com.alibaba.dashscope.aigc.imagegeneration.*;
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.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro 组图生成 - 异步调用示例(新加坡地域)
 */
public class Main {

    static {
        // 以下为新加坡地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64编码函数 ---
    // base64编码格式为 data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static ImageGenerationResult waitTask(String taskId)
            throws ApiException, NoApiKeyException {
        ImageGeneration imageGeneration = new ImageGeneration();
        return imageGeneration.wait(taskId, apiKey);
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 图像输入方式说明(图生组图场景):
         * 以下提供了三种图片输入方式,三选一即可
         * 1. 使用公网URL - 适合已有公开可访问的图片
         * 2. 使用本地文件 - 适合本地开发测试
         * 3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
         */
        // 【方式一】使用公网图片 URL
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // 【方式二】使用本地文件(支持绝对路径和相对路径)
        // 格式要求:file:// + 文件路径
        // String image1 = "file:///path/to/your/image.png";

        // 【方式三】使用Base64编码的图片
        // String image1 = encodeFile("/path/to/your/image.png");

        // 构建文本输入消息(支持文生组图以及图生组图,此处以文生组图为例)
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。")
                )).build();
        // 图生组图场景:取消以下注释并注释掉上方纯文本构建
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "参考图片风格生成四季组图"),
        //                 Collections.singletonMap("image", image1)
        //         )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .enableSequential(true)
                .n(4)
                .size("2K") // wan2.7-image-pro仅文生图场景支持4K分辨率,图像编辑和组图生成支持最高2K分辨率
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult taskResult = null;
        try {
            System.out.println("----async call, creating task----");
            taskResult = imageGeneration.asyncCall(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("Task created: " + JsonUtils.toJson(taskResult));

        // 等待任务完成
        String taskId = taskResult.getOutput().getTaskId();
        ImageGenerationResult result = waitTask(taskId);
        // 提取结果图片URL并保存到本地
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // 结果URL有效期为24小时,请及时下载
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}
Response example
  1. Response example of creating a node
{
    "requestId": "7d026dc1-e8c9-9caa-84ac-e82e2da97xxx",
    "output": {
        "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
        "task_status": "PENDING"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}
  1. Response example of querying the node result

The URL is valid for 24 hours. Download and save the images in a timely manner.

{
    "requestId": "daea7295-4ce0-928a-9a11-4d2bea058xxx",
    "usage": {
        "input_tokens": 720,
        "output_tokens": 11,
        "total_tokens": 731,
        "image_count": 4,
        "size": "2048*2048"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        },
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "task_id": "2de18c56-c151-4b80-8105-1d164733exxx",
        "task_status": "SUCCEEDED",
        "finished": true,
        "submit_time": "2026-03-31 19:49:53.124",
        "scheduled_time": "2026-03-31 19:49:53.175",
        "end_time": "2026-03-31 19:50:53.160"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Billing and rate limits

  • For the free quota and unit prices of the model, see Model price.
  • For model rate limits, see Wan.
  • Billing: You are billed based on the number of images successfully generated. Failed model calls or processing errors incur no fees and do not consume the free quota for new users.

Error codes

If a model call fails and returns an error message, see Error codes for troubleshooting.