Skip to main content

Wan2.7 - image generation and editing

Wan2.7-Image supports 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

Wan 2.7 image Pro. Supports 4K output for text-to-image generation (not for image sets).

Image format: PNG.

For image resolution and dimensions, see the size parameter.

wan2.7-image

Wan 2.7 image. Faster generation.

Before you call a model, check Model list and prices for regional model availability.

Prerequisites

Obtain an API key and export the API key as an environment variable.
The China (Beijing) and Singapore regions have separate API keys and request endpoints. They cannot be used interchangeably. Cross-region calls lead to authentication failures or service errors.
Model Studio provides workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend that you migrate 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
In the URLs, {WorkspaceId} is your workspace ID, which you can view on the Workspace details page in the Model Studio console. The existing domain remains available.

HTTP synchronous

Returns the result in a single request. Recommended for most use cases.
  • Beijing
  • Singapore
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generationReplace {WorkspaceId} with your actual workspace ID.

Request parameters

  • Text-to-image
  • Image editing
  • Interactive editing
  • Image set generation
The wan2.7-image-pro model supports 4K resolution for text-to-image generation only. Image editing and image set generation support up to 2K resolution.
curl --location 'https://{WorkspaceId}.cn-beijing.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
    }
}'
Headers
Content-Type string (Required)The content type of the request. Must be application/json.
Authorization string (Required)Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
Request body
model string (Required)The model name. Valid values: wan2.7-image-pro, wan2.7-image.
input object (Required)The input object.

Properties

messages array (Required)An array of request content. Currently, only single-turn conversations are supported: only one set of role and content parameters can be passed in, and multi-turn conversations are not supported.

Properties

role string (Required)The message role. Must be user.content array (Required)An array of message content.

Properties

text stringThe text prompt. Supports Chinese and English. Maximum 5,000 characters. Each character, letter, number, or symbol counts as one. Excess characters are truncated.image stringThe URL or Base64-encoded string of the input image.Image limits:
  • Image format: JPEG, JPG, PNG (transparent channels are not supported), BMP, WEBP.
  • Image resolution: The width and height of the image both range from [240, 8000] pixels, and the aspect ratio ranges from [1:8, 8:1].
  • File size: No more than 20 MB.
Image number limits:
  • You can input 0 to 9 images.
  • When you input multiple images, you must pass multiple image objects in the content array. The order of the objects in the array determines the order of the images.
Supported input formats:
  1. Use a publicly accessible URL
    • Supports HTTP or HTTPS protocols.
    • Example: http://wanx.alicdn.com/material/xxx.jpeg.
  2. Pass a Base64-encoded image string
    • Format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (This is for illustration only. You must pass the complete string.)
    • For more information, see Image input methods.
parameters object (Optional)Model parameter settings.

Properties

bbox_list array[array[array[integer]]] (Optional)The bounding box area for interactive editing.
  • The length of the list must match the number of input images. If an image does not require editing, pass an empty list [] in the corresponding position.
  • Coordinate format: [x1, y1, x2, y2] (top-left x, top-left y, bottom-right x, bottom-right y). Use absolute pixel coordinates of the original image. The top-left coordinate is (0, 0).
  • A single image supports a maximum of two bounding boxes.
Example: Input 3 images, where the second image has no bounding box and the first image has two bounding boxes:
[
  [[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): The default output mode.
  • true: The image set output mode.
size string (Optional)The output image resolution. Supports two mutually exclusive methods:Model: wan2.7-image-pro
  • Method 1: Specify the output image resolution (Recommended)
    • Supports 1K, 2K (default), and 4K specifications.
    • Scope of application:
      • Text-to-image (no image input, not for image set generation): Supports 1K, 2K, and 4K.
      • Other scenarios: Supports 1K and 2K.
    • Total pixels for each specification: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096
    • Image aspect ratio:
      • When an image is input: The output aspect ratio matches the input image (the last one if multiple images are input) and is scaled to the selected resolution.
      • When no image is input: The output is a square image.
  • Method 2: Specify the width and height in pixels for the generated image
    • Text-to-image: The total number of pixels is between [768768, 40964096], with an aspect ratio range of [1:8, 8:1].
    • Other scenarios: The total number of pixels is between [768768, 20482048], with an aspect ratio range of [1:8, 8:1].
Model: wan2.7-image
  • Method 1: Specify the output image resolution (Recommended)
    • Supports 1K and 2K (default) specifications. 4K is not supported.
  • Method 2: Specify the width and height in pixels for the generated image
    • In all scenarios, the total number of pixels is between [768768, 20482048], with an aspect ratio range of [1:8, 8:1].
The pixel values of the output image may have minor differences from the specified values.
n integer (Optional)
The n parameter directly affects cost: unit price × number of successfully generated images. Confirm the model pricing before calling.
  • When image set mode is disabled, this value represents the number of images to generate. The range is 1 to 4. Defaults to 1.
  • When image set mode is enabled, this value represents the maximum number of images to generate. The range is 1 to 12. Defaults to 12. The actual number is determined by the model and will not exceed n.
thinking_mode boolean (Optional)Enables thinking mode. Defaults to true. This parameter is effective only when image set mode is disabled and no image is input. When enabled, the model enhances its inference capabilities to improve output quality, but this increases generation time.color_palette array (Optional)A custom color theme. An array of objects, each with a hexadecimal color and a ratio. Must include 3 to 10 colors. 8 colors recommended.This is available only when image set mode is disabled (enable_sequential=false).

Properties

hex string (Required)The color value in hexadecimal (HEX) format.ratio string (Required)The percentage of the color. Must be accurate to two decimal places (such as "25.00%"). The sum of all ratio values must be 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)Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated".
  • false (default)
  • true
seed integer (optional)Random number seed. Valid range: [0,2147483647].Using the same seed yields similar outputs. If omitted, the algorithm uses a random seed.Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

  • Successful task execution
  • Abnormal task execution
Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.
{
    "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.

Properties

choices arrayThe output content generated by the model.

Properties

finish_reason stringThe reason the task stopped. stop indicates natural completion.message objectThe message returned by the model.

Properties

rolestringThe message role. Always assistant.contentarray

Properties

type stringValue: image.image stringThe URL of the generated image. Format: PNG.The link is valid for 24 hours. Download the image promptly.
finished booleanIndicates whether the task is finished.
  • true: finished.
  • false: not finished.
usage objectUsage statistics for the request. Only successful results are counted.

Properties

image_count integerThe number of generated images.size stringThe resolution of the generated image. Example: 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_idstringUnique request identifier for tracing and troubleshooting.
codestringError code. Returned only for failed requests. See Error codes.
messagestringDetailed error message. Returned only for failed requests. See Error codes.

HTTP asynchronous

Best for long-running tasks. Submit a task, then poll for status and results.

Step 1: Create a task to get the task ID

  • Beijing
  • Singapore
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generationReplace {WorkspaceId} with your actual workspace ID.

Request parameters

  • Text-to-image
  • Image editing
  • Interactive editing
  • Image set generation
The wan2.7-image-pro model supports 4K resolution for text-to-image generation only. Image editing and image set generation support up to 2K resolution.
curl --location 'https://{WorkspaceId}.cn-beijing.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
    }
}'
Headers
Content-Type string (Required)The content type of the request. Must be application/json.
Authorization string (Required)Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
X-DashScope-Async string (Required)Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be set to enable.
If this request header is missing, the error "current user api does not support synchronous calls" is returned.
Request body
model string (Required)The model name. Valid values: wan2.7-image-pro, wan2.7-image.
input object (Required)The input object.

Properties

messages array (Required)An array of request content. Currently, only single-turn conversations are supported: only one set of role and content parameters can be passed in, and multi-turn conversations are not supported.

Properties

role string (Required)The message role. Must be user.content array (Required)An array of message content.

Properties

text stringThe text prompt. Supports Chinese and English. Maximum 5,000 characters. Each character, letter, number, or symbol counts as one. Excess characters are truncated.image stringThe URL or Base64-encoded string of the input image.Image limits:
  • Image format: JPEG, JPG, PNG (transparent channels are not supported), BMP, WEBP.
  • Image resolution: The width and height of the image both range from [240, 8000] pixels, and the aspect ratio ranges from [1:8, 8:1].
  • File size: No more than 20 MB.
Image number limits:
  • You can input 0 to 9 images.
  • When you input multiple images, you must pass multiple image objects in the content array. The order of the objects in the array determines the order of the images.
Supported input formats:
  1. Use a publicly accessible URL
    • Supports HTTP or HTTPS protocols.
    • Example: http://wanx.alicdn.com/material/xxx.jpeg.
  2. Pass a Base64-encoded image string
    • Format: data:{MIME_type};base64,{base64_data}
    • Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (This is for illustration only. You must pass the complete string.)
    • For more information, see Image input methods.
parameters object (Optional)Model parameter settings.

Properties

bbox_list array[array[array[integer]]] (Optional)The bounding box area for interactive editing.
  • The length of the list must match the number of input images. If an image does not require editing, pass an empty list [] in the corresponding position.
  • Coordinate format: [x1, y1, x2, y2] (top-left x, top-left y, bottom-right x, bottom-right y). Use absolute pixel coordinates of the original image. The top-left coordinate is (0, 0).
  • A single image supports a maximum of two bounding boxes.
Example: Input 3 images, where the second image has no bounding box and the first image has two bounding boxes:
[
  [[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): The default output mode.
  • true: The image set output mode.
size string (Optional)The output image resolution. Supports two mutually exclusive methods:Model: wan2.7-image-pro
  • Method 1: Specify the output image resolution (Recommended)
    • Supports 1K, 2K (default), and 4K specifications.
    • Scope of application:
      • Text-to-image (no image input, not for image set generation): Supports 1K, 2K, and 4K.
      • Other scenarios: Supports 1K and 2K.
    • Total pixels for each specification: 1K: 1024×1024, 2K: 2048×2048, 4K: 4096×4096
    • Image aspect ratio:
      • When an image is input: The output aspect ratio matches the input image (the last one if multiple images are input) and is scaled to the selected resolution.
      • When no image is input: The output is a square image.
  • Method 2: Specify the width and height in pixels for the generated image
    • Text-to-image: The total number of pixels is between [768768, 40964096], with an aspect ratio range of [1:8, 8:1].
    • Other scenarios: The total number of pixels is between [768768, 20482048], with an aspect ratio range of [1:8, 8:1].
Model: wan2.7-image
  • Method 1: Specify the output image resolution (Recommended)
    • Supports 1K and 2K (default) specifications. 4K is not supported.
  • Method 2: Specify the width and height in pixels for the generated image
    • In all scenarios, the total number of pixels is between [768768, 20482048], with an aspect ratio range of [1:8, 8:1].
The pixel values of the output image may have minor differences from the specified values.
n integer (Optional)
The n parameter directly affects cost: unit price × number of successfully generated images. Confirm the model pricing before calling.
  • When image set mode is disabled, this value represents the number of images to generate. The range is 1 to 4. Defaults to 1.
  • When image set mode is enabled, this value represents the maximum number of images to generate. The range is 1 to 12. Defaults to 12. The actual number is determined by the model and will not exceed n.
thinking_mode boolean (Optional)Enables thinking mode. Defaults to true. This parameter is effective only when image set mode is disabled and no image is input. When enabled, the model enhances its inference capabilities to improve output quality, but this increases generation time.color_palette array (Optional)A custom color theme. An array of objects, each with a hexadecimal color and a ratio. Must include 3 to 10 colors. 8 colors recommended.This is available only when image set mode is disabled (enable_sequential=false).

Properties

hex string (Required)The color value in hexadecimal (HEX) format.ratio string (Required)The percentage of the color. Must be accurate to two decimal places (such as "25.00%"). The sum of all ratio values must be 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)Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated".
  • false (default)
  • true
seed integer (optional)Random number seed. Valid range: [0,2147483647].Using the same seed yields similar outputs. If omitted, the algorithm uses a random seed.Note: Image generation is probabilistic. Even with the same seed, results may vary.

Response parameters

  • Successful response
  • 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.

Properties

task_id stringThe task ID. Valid for queries for 24 hours.task_status stringThe status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.
request_idstringUnique request identifier for tracing and troubleshooting.
codestringError code. Returned only for failed requests. See Error codes.
messagestringDetailed error message. Returned only for failed requests. See Error codes.

Step 2: Query the result by task ID

  • Beijing
  • Singapore
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Request parameters

  • Query task result
Replace {task_id} with the task_id value returned by the previous API call. The task_id is valid for queries for 24 hours, Replace {WorkspaceId} with your actual workspace ID.
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Headers
Authorization string (Required)Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
Path parameters
task_id string (Required)The ID of the task.

Response parameters

  • Successful task execution
  • Abnormal task execution
Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.
{
    "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.

Properties

task_id stringThe task ID. Valid for queries for 24 hours.task_status stringThe status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.
Status transitions during polling:
  • PENDING (Queuing) → RUNNING (Processing)→ SUCCEEDED (Success) / FAILED (Failed).
  • The status on 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 retry.
submit_time stringTask submission time. The format is YYYY-MM-DD HH:mm:ss.SSS.scheduled_time stringTask execution time. The format is YYYY-MM-DD HH:mm:ss.SSS.end_time stringTask completion time. The format is YYYY-MM-DD HH:mm:ss.SSS.finished booleanIndicates whether the task is finished.
  • true: finished.
  • false: not finished.
choices arrayThe output content generated by the model.

Properties

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

Properties

rolestringThe message role. Always assistant.contentarray

Properties

type stringThe type of the output. The enumerated values are text and image.text stringThe generated text.image stringThe URL of the generated image. Format: PNG.The link is valid for 24 hours. Download the image promptly.
usage objectUsage statistics for the request. Only successful results are counted.

Properties

image_count integerThe number of generated images.size stringThe resolution of the generated image. Example: 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_idstringUnique request identifier for tracing and troubleshooting.
codestringError code. Returned only for failed requests. See Error codes.
messagestringDetailed error message. Returned only for failed requests. See Error codes.

Python SDK call

The SDK parameter naming is basically the same as that of the HTTP API. The task may take a long time. The SDK has encapsulated the HTTP asynchronous call process and supports both synchronous and asynchronous calls.
The specific time consumption depends on the number of queued tasks and service execution. Please wait patiently when obtaining the results.
Make sure the DashScope Python SDK version is 2.1.0 or later before running the following code. For updates, see Install SDK.
The base_url and API Key are not universal across regions. The following examples use the Beijing region:
  • China (Beijing)
  • Singapore
https://{WorkspaceId}.cn-beijing.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

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

# --- 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
    }
}

Sequential image generation

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

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

# --- 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
    }
}

Java SDK

The SDK parameter naming is basically the same as that of the HTTP API. The task may take a long time. The SDK has encapsulated the HTTP asynchronous call process and supports both synchronous and asynchronous calls.
Make sure the DashScope Java SDK version is 2.22.13 or later; otherwise, some of the parameters used in this topic may not be supported.
  • China (Beijing)
  • Singapore
https://{WorkspaceId}.cn-beijing.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 图像编辑 - 同步调用示例
 */
public class Main {

    static {
        // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/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 image 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;

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

    static {
        // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    }

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/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 image 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 limiting

  • For the model's free quota and unit price, see Model pricing.
  • For model rate limiting, see Wanxiang.
  • Billing details: You are billed based on the number of images successfully generated. Failed calls and processing errors do not incur charges or consume your free quota for new users.

Error codes

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