Skip to main content

Wan Image Generation and Editing 2.7 API Reference

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

Before 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.
The 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.
Alibaba 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
  • Beijing
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generationWhen calling, replace {WorkspaceId} with your actual workspace ID.

Request parameters

  • Text-to-image
  • Image editing
  • Interactive editing
  • Group image generation
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
        }
    }'

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 stringThe 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 stringThe 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)
n 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%.
"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 execution exception
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"
}
output objectTask output information.

property

choices arrayThe output content generated by the model.

property

finish_reason stringThe reason the task stopped. It is stop when the task stops naturally.message objectThe message returned by the model.

property

rolestringThe role of the message, fixed as assistant.contentarray

property

type stringThe type of the output, fixed as image.image stringThe 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 booleanWhether the task has ended.
  • true: Ended.
  • false: Not ended.
usage objectOutput information statistics. Only successful results are counted.

property

image_count integerThe number of generated images.size stringThe resolution of the generated image. Example value: 1376*768.input_tokens integerThe number of input tokens (not billed). Billing is based on the number of images.output_tokens integerThe number of output tokens (not billed). Billing is based on the number of images.total_tokensintegerThe total number of tokens (not billed). Billing is based on the number of images.
request_idstringThe unique identifier of the request. It can be used for tracing request details and troubleshooting.
codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
messagestringThe 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
  • Beijing
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generationWhen calling, replace {WorkspaceId} with your actual workspace ID.

Request parameters

  • Text-to-image
  • Image editing
  • Interactive editing
  • Group image generation
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
        }
    }'

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.
If 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 stringThe 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 stringThe 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)
n 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%.
"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
  • Error 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"
}
output objectTask output information.

property

task_id stringThe task ID. The validity period for queries is 24 hours.task_status stringThe 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_idstringThe unique identifier of the request. It can be used for tracing request details and troubleshooting.
codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
messagestringThe 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
  • 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 execution exception
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
    }
}
output objectTask output information.

property

task_id stringThe task ID. The validity period for queries is 24 hours.task_status stringThe 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 stringThe time when the node was submitted. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.scheduled_time stringThe node execution time. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.end_time stringThe time when the node was completed. The time zone is UTC+8, in the format YYYY-MM-DD HH:mm:ss.SSS.finished booleanWhether the task has ended.
  • true: Ended.
  • false: Not ended.
choices arrayThe output content generated by the model.

property

finish_reason stringThe reason the node stopped; stop when it stops naturally.message objectThe message returned by the model.

property

rolestringThe role of the message, fixed as assistant.contentarray

property

type stringThe type of the output. Enumerated values: text and image.text stringThe generated text.image stringThe 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 objectOutput information statistics. Only successful results are counted.

property

image_count integerThe number of generated images.size stringThe resolution of the generated image. Example value: 1376*768.input_tokens integerThe number of input tokens (not billed). Billing is based on the number of images.output_tokens integerThe number of output tokens (not billed). Billing is based on the number of images.total_tokensintegerThe total number of tokens (not billed). Billing is based on the number of images.
request_idstringThe unique identifier of the request. It can be used for tracing request details and troubleshooting.
codestringThe error code returned when the request fails. This parameter is not returned when the request succeeds. For more information, see Error codes.
messagestringThe 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.
Make 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
  • China (Beijing)
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1When calling, replace {WorkspaceId} with your actual Workspace ID.

Image editing

  • Synchronous call
  • Asynchronous call
Request example
import os
import base64
import mimetypes
import urllib.request
import dashscope

# This configuration is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an 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 encoding function ---
# The Base64 encoding format is 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编码 - 适合私有图片或需要加密传输的场景
"""
# [Method 1] Use a public image 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"

# [Method 2] Use a local file (supports absolute and relative paths)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [Method 3] Use a Base64-encoded image
# 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 submits the task and waits, returning the completed task result directly
job = client.images.generate(
    model="wan2.7-image-pro",
    prompt="把图2的涂鸦喷绘在图1的汽车上",
    # Reference images; local files are supported, such as "file:///path/to/your/car.png"
    image_urls=[image_1, image_2],
    watermark=False,
    n=1,
    size="2K",  # wan2.7-image-pro supports 4K resolution only for text-to-image generation. Image editing and multi-image generation support up to 2K resolution.
)

# Extract the result image URL and save the image to a local file.
for i, image_url in enumerate(job.image_urls):
    file_name = f"output_{i}.png"
    # The result URL is valid for 24 hours. Download the image in a timely manner.
    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
    }
}

Sequential image generation

  • Synchronous call
  • Asynchronous call
Request example
import os
import base64
import mimetypes
import urllib.request
import dashscope

# This configuration is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an 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 encoding function ---
# The Base64 encoding format is 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编码 - 适合私有图片或需要加密传输的场景
"""
# [Method 1] Use a public image URL
# image_1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp"

# [Method 2] Use a local file (supports absolute and relative paths)
# image_1 = "file:///path/to/your/image.png"

# [Method 3] Use a Base64-encoded image
# image_1 = encode_file("/path/to/your/image.png")

print("----sync call, please wait a moment----")
# generate submits the task and waits, returning the completed task result directly
job = client.images.generate(
    model="wan2.7-image-pro",
    prompt="电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。",
    # For image-to-image series generation, uncomment the following lines, pass the reference image, and change the prompt above to generate a four-season image series using the reference style
    # image_urls=[image_1],
    parameters={"enable_sequential": True},  # Generate an image series
    n=4,
    size="2K",  # wan2.7-image-pro supports 4K resolution only for text-to-image generation. Image editing and multi-image generation support up to 2K resolution.
)

# Extract the result image URL and save the image to a local file.
for i, image_url in enumerate(job.image_urls):
    file_name = f"output_{i}.png"
    # The result URL is valid for 24 hours. Download the image in a timely manner.
    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
    }
}

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.
Make 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
  • China (Beijing)
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1When calling, replace {WorkspaceId} with your actual Workspace ID.

Image editing

  • Synchronous call
  • 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 Image Editing - Synchronous Call Example
 */
public class Main {

    static {
        // The following URL is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 encoding function ---
    // The Base64 encoding format is 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 {
        /*
         * Description of image input methods:
         * The following three image input methods are provided. You can choose one of them.
         * 1. Use a public URL - suitable for publicly accessible images.
         * 2. Local file: Suitable for local development and testing.
         * 3. Base64 encoding: Best for private images or when data must be securely transmitted.
         */
        // [Method 1] Use a public image 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";

        // [Method 2] Use a local file (supports absolute and relative paths)
        // Format: file:// + file path
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // [Method 3] Use a Base64-encoded image
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // Build a multi-image input message.
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // Multi-image input is supported. You can provide multiple reference images.
                        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 supports 4K resolution only for text-to-image generation. Image editing and multi-image generation support up to 2K resolution.
                .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());
        }
        // Extract the result image URL and save the image to a local file.
        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";
                    // The result URL is valid for 24 hours. Download the image in a timely manner.
                    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": ""
}

Sequential image generation

  • Synchronous call
  • 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;

/**
 * An example of using wan2.7-image-pro for image series generation through synchronous calls in the Singapore region.
 */
public class Main {

    static {
        // The following URL is for the Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. The base_url varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 encoding function ---
    // The Base64 encoding format is 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 {
        /*
         * Image input methods (for image-to-image series generation):
         * The following three image input methods are provided. You can choose one of them.
         * 1. Use a public URL - suitable for publicly accessible images.
         * 2. Local file: Suitable for local development and testing.
         * 3. Base64 encoding: Best for private images or when data must be securely transmitted.
         */
        // [Method 1] Use a public image URL
        // String image1 = "https://img.alicdn.com/imgextra/i4/O1CN01IM44WN23dq5uY1yla_!!6000000007279-49-tps-1024-1024.webp";

        // [Method 2] Use a local file (supports absolute and relative paths)
        // Format: file:// + file path
        // String image1 = "file:///path/to/your/image.png";

        // [Method 3] Use a Base64-encoded image
        // String image1 = encodeFile("/path/to/your/image.png");

        // Build the text input message. This supports both text-to-image and image-to-image series generation. This example demonstrates text-to-image series generation.
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Collections.singletonList(
                        Collections.singletonMap("text", "电影感组图,记录同一只流浪橘猫,特征必须前后一致。第一张:春天,橘猫穿梭在盛开的樱花树下;第二张:夏天,橘猫在老街的树荫下乘凉避暑;第三张:秋天,橘猫踩在满地的金色落叶上;第四张:冬天,橘猫在雪地上走留下足迹。")
                )).build();
        // For image-to-image series generation, uncomment the following code and comment out the plain text message builder above.
        // ImageGenerationMessage message = ImageGenerationMessage.builder()
        //         .role("user")
        //         .content(Arrays.asList(
        //                 Collections.singletonMap("text", "Generate a four-season image series based on the style of the reference image."),
        //                 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 supports 4K resolution only for text-to-image generation. Image editing and multi-image generation support up to 2K resolution.
                .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());
        }
        // Extract the result image URL and save the image to a local file.
        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";
                    // The result URL is valid for 24 hours. Download the image in a timely manner.
                    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": ""
}

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.