All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan - general image editing API reference

Last Updated:Oct 17, 2025

This topic describes the input and output parameters of the Wan general image editing model.

Important

This model is available only in the China (Beijing) region. To use this model, you must use an API key for the China (Beijing) region.

The model can perform various image editing tasks based on simple instructions. It is suitable for scenarios such as outpainting, watermark removal, style transfer, image restoration, and image enhancement. The following features are supported:

  • Image stylization: Global and local stylization.

  • Image content editing: Instruction-based editing (add or modify image content based on instructions without specifying a region), inpainting (add, delete, or modify image content in a specified region), and text and watermark removal (Chinese and English).

  • Image size and resolution optimization: Outpainting (extend an image based on a specified ratio) and image super-resolution (high-definition upscaling).

  • Image color processing: Image colorization (convert a black-and-white or grayscale image to a color image).

  • Generation based on a reference image: Line art to image (extracts line art from an input image to generate a new image) and cartoon character reference-based generation.

Related guide: Image editing - Wan

Model overview

Model

Unit price

Rate limit (shared by Alibaba Cloud accounts and RAM users)

RPS limit for task submission

Number of concurrent tasks

wanx2.1-imageedit

$0.020070/image

2

2

Performance showcase

Feature

Input image

Input prompt

Output image

Global stylization

image

Convert to French picture book style

image

Local stylization

image

Change the house to a wooden style.

image

Instruction-based editing

image

Change the girl's hair to red.

image

Inpainting

Input image

image

Input mask image (The white area is the mask area)

image

A ceramic rabbit holding a ceramic flower.

Output image

image

Text and watermark removal

image

Remove the text from the image.

image

Outpainting

20250319105917

A green fairy.

image

Image super-resolution

Blurry image

image

Image super-resolution.

Clear image

image

Image colorization

image

Blue background, yellow leaves.

image

Line art to image

Input image

image

A living room in a minimalist Nordic style.

Extract the line art from the original image and generate a new image

image

Generate image from cartoon character reference

Input reference image (cartoon character)

image

The cartoon character cautiously peeks out, peering at a brilliant blue gem in the room.

Output image

image

Prerequisites

You can call the Wan general image editing API using HTTP and the DashScope SDK.

Before making a call, obtain an API key and set the API key as an environment variable.

To make calls using the SDK, install the DashScope SDK. The SDK is available for Python and Java.

HTTP

Image models can take a long time to process. To avoid request timeouts, HTTP calls support only asynchronous retrieval of model results. You must make two requests:

  1. Create a task to obtain a task ID: First, send a request to create a task. This request returns a task ID (task_id).

  2. Query the result by task ID: Use the task ID from the previous step to query the task status and result. If the task runs successfully, an image URL is returned. The URL is valid for 24 hours.

Note

After you create a task, the task is added to a queue and waits for scheduling. You must then call the "query result by task ID" API to retrieve the task status and result.

The general image editing model requires approximately 5 to 15 seconds to process a request. The actual processing time depends on the number of tasks in the queue and the network conditions.

Step 1: Create a task and obtain a task ID

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

Request parameters

Global stylization

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "stylization_all",
    "prompt": "Convert to French picture book style",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg"
  },
  "parameters": {
    "n": 1
  }
}'

Pass a local file (base64)

The following example shows how to pass parameters in Base64 for global stylization.

Because the Base64-encoded string is long, download image_base64 and copy the entire content as the value of the base_image_url parameter.

For more information about the data format, see Input methods.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "stylization_all",
    "prompt": "Convert to French picture book style",
    "base_image_url": "data:image/jpeg;base64,/9j/4AAQSkZJR......"
  },
  "parameters": {
    "n": 1
  }
}'

Local stylization

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "stylization_local",
    "prompt": "Change the house to a wooden board style.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/stylization_local_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Instruction-based editing

Description: Add or modify image content based on instructions without specifying a region.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "description_edit",
    "prompt": "Change the girl's hair to red.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/description_edit_2.png"
  },
  "parameters": {
    "n": 1
  }
}'

Inpainting

Description: Add, delete, or modify image content in a specified region.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "description_edit_with_mask",
    "prompt": "A ceramic rabbit holding a ceramic flower.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3.jpeg",
    "mask_image_url": "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3_mask.png"
  },
  "parameters": {
    "n": 1
  }
}'

Text and watermark removal

Description: This feature supports removing text and watermarks in Chinese and English.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "remove_watermark",
    "prompt": "Remove the text from the image",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/remove_watermark_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Outpainting

Description: This feature supports outpainting in the up, down, left, and right directions based on a specified ratio.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "expand",
    "prompt": "A green fairy",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/expand_2.jpg"
  },
  "parameters": {
    "top_scale": 1.5,
    "bottom_scale": 1.5,
    "left_scale": 1.5,
    "right_scale": 1.5,
    "n": 1
  }
}'

Image super-resolution

Description: This feature supports high-definition upscaling of blurry images.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "super_resolution",
    "prompt": "Image super-resolution.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/super_resolution_1.jpeg"  
  },
  "parameters": {
    "upscale_factor": 2,
    "n": 1
  }
}'

Image colorization

Description: Convert a black-and-white or grayscale image to a color image.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "colorization",
    "prompt": "Blue background, yellow leaves.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/colorization_1.jpeg"  
  },
  "parameters": {
    "n": 1
  }
}'

Line art to image

Description: Extracts line art from the input image and generates a new image based on the extracted art.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "doodle",
    "prompt": "A living room in a minimalist Nordic style.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/doodle_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Generate image from cartoon character reference

Description: This feature supports generating an image based on a cartoon character reference.

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wanx2.1-imageedit",
  "input": {
    "function": "control_cartoon_feature",
    "prompt": "The cartoon character cautiously peeks out, peering at a brilliant blue gem in the room.",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/control_cartoon_feature_1.png"
  },
  "parameters": {
    "n": 1
  }
}'
Request headers

Content-Type string (Required)

The content type of the request. Set this parameter to application/json.

Authorization string (Required)

The identity authentication credentials for the request. This API uses an Model Studio API key for identity authentication. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

The asynchronous processing configuration parameter. HTTP requests support only asynchronous processing. You must set this parameter to enable.

Important

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

Request body

model string (Required)

The model name. Example: wanx2.1-imageedit.

input object (Required)

The basic input information, such as the prompt.

Properties

prompt string (Required)

The prompt that describes the expected elements and visual features in the generated image.

The prompt can be in Chinese or English and contain no more than 800 characters. Each Chinese character or letter is counted as one character. Any text exceeding this limit is truncated.

The prompts for different features vary. Refer to the prompt tips for each feature.

function string (Required)

The image editing feature. The following features are supported:

  • stylization_all: Global stylization. Two styles are supported. Styles and prompt tips

  • stylization_local: Local stylization. Eight styles are supported. Styles and prompt tips

  • description_edit: Instruction-based editing. You can edit an image based on instructions. This method is recommended for simple editing tasks. Prompt tips

  • description_edit_with_mask: Inpainting. You need to specify the editing area. This method is suitable for scenarios that require precise control over the editing scope. Prompt tips

  • remove_watermark: Text and watermark removal. Prompt tips

  • expand: Outpainting. Prompt tips

  • super_resolution: Image super-resolution. Prompt tips

  • colorization: Image colorization. Prompt tips

  • doodle: Line art to image. Prompt tips

  • control_cartoon_feature: Generate image from cartoon character reference. Prompt tips

base_image_url string (Required)

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

Image constraints:

  • Image format: JPG, JPEG, PNG, BMP, TIFF, or WEBP.

  • Image resolution: The width and height of the image must be within the range of [512, 4096] pixels.

  • Image size: No more than 10 MB.

  • The URL cannot contain Chinese characters.

Input image details:

  1. Use a publicly accessible URL

    • HTTP or HTTPS is supported.

    • Example: http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg.

  2. A string that contains the Base64-encoded image.

    • Data format: data:{MIME_type};base64,{base64_data}.

    • Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ.......

    • The encoded image data in the example is incomplete and for demonstration purposes only. For more information, see Input methods.

mask_image_url string (Optional)

This parameter is required only when function is set to description_edit_with_mask (inpainting). This parameter is not required for other features.

The URL or Base64-encoded data of the mask image.

You can pass a publicly accessible URL (HTTP/HTTPS) or a Base64-encoded image. For more information, see Input methods.

Mask image requirements:

  • Image resolution: The resolution must be the same as that of the image specified by base_image_url. The width and height of the image must be within the range of [512, 4096] pixels.

  • Image format: JPG, JPEG, PNG, BMP, TIFF, or WEBP.

  • Image size: No more than 10 MB.

  • The URL cannot contain Chinese characters.

Mask area color requirements:

  • White area: Indicates the part to be edited. It must be pure white (RGB value: [255,255,255]). Otherwise, it may not be correctly identified.

  • Black area: Indicates the part that does not need to be changed. It must be pure black (RGB value: [0,0,0]). Otherwise, it may not be correctly identified.

To obtain a mask image, you can use Photoshop or other tools to generate a black-and-white mask image.

parameters object (Optional)

The image editing parameters.

Properties

General

n integer (Optional)

The number of images to generate. Valid values: 1 to 4. Default value: 1.

seed integer (Optional)

The random number seed, which is used to control the randomness of the content generated by the model. The value of the seed parameter must be in the range of [0, 2147483647].

If you do not provide this parameter, the algorithm automatically generates a random number as the seed. To generate relatively stable content, use the same seed parameter value.

watermark bool (Optional)

Specifies whether to add a watermark. The watermark is located in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

Global stylization

n integer (Optional)

The number of images to generate. Valid values: 1 to 4. Default value: 1.

seed integer (Optional)

The random number seed, which is used to control the randomness of the content generated by the model. The value of the seed parameter must be in the range of [0, 2147483647].

If you do not provide this parameter, the algorithm automatically generates a random number as the seed. To generate relatively stable content, use the same seed parameter value.

watermark bool (Optional)

Specifies whether to add a watermark. The watermark is located in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

strength float (Optional)

Specify this parameter when function is set to stylization_all (global stylization).

Controls the degree of image modification. The value must be in the range of [0.0, 1.0]. Default value: 0.5.

A value closer to 0 indicates a result closer to the original image. A value closer to 1 indicates a greater degree of modification to the original image.

Instruction-based editing

n integer (Optional)

The number of images to generate. Valid values: 1 to 4. Default value: 1.

seed integer (Optional)

The random number seed, which is used to control the randomness of the content generated by the model. The value of the seed parameter must be in the range of [0, 2147483647].

If you do not provide this parameter, the algorithm automatically generates a random number as the seed. To generate relatively stable content, use the same seed parameter value.

watermark bool (Optional)

Specifies whether to add a watermark. The watermark is located in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

strength float (Optional)

Specify this parameter when function is set to description_edit (instruction-based editing).

Controls the degree of image modification. The value must be in the range of [0.0, 1.0]. Default value: 0.5.

A value closer to 0 indicates a result closer to the original image. A value closer to 1 indicates a greater degree of modification to the original image.

Outpainting

n integer (Optional)

The number of images to generate. Valid values: 1 to 4. Default value: 1.

seed integer (Optional)

The random number seed, which is used to control the randomness of the content generated by the model. The value of the seed parameter must be in the range of [0, 2147483647].

If you do not provide this parameter, the algorithm automatically generates a random number as the seed. To generate relatively stable content, use the same seed parameter value.

watermark bool (Optional)

Specifies whether to add a watermark. The watermark is located in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

top_scale float (Optional)

Specify this parameter only when function is set to expand (outpainting).

The image is centered and expanded upward based on the specified ratio. Default value: 1.0. The value must be in the range of [1.0, 2.0].

bottom_scale float (Optional)

Specify this parameter only when function is set to expand (outpainting).

The image is centered and expanded downward based on the specified ratio. Default value: 1.0. The value must be in the range of [1.0, 2.0].

left_scale float (Optional)

Specify this parameter only when function is set to expand (outpainting).

The image is centered and expanded to the left based on the specified ratio. Default value: 1.0. The value must be in the range of [1.0, 2.0].

right_scale float (Optional)

Specify this parameter only when function is set to expand (outpainting).

The image is centered and expanded to the right based on the specified ratio. Default value: 1.0. The value must be in the range of [1.0, 2.0].

Image super-resolution

n integer (Optional)

The number of images to generate. Valid values: 1 to 4. Default value: 1.

seed integer (Optional)

The random number seed, which is used to control the randomness of the content generated by the model. The value of the seed parameter must be in the range of [0, 2147483647].

If you do not provide this parameter, the algorithm automatically generates a random number as the seed. To generate relatively stable content, use the same seed parameter value.

watermark bool (Optional)

Specifies whether to add a watermark. The watermark is located in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

upscale_factor integer (Optional)

Specify this parameter only when function is set to super_resolution (image super-resolution).

Specifies the magnification factor for image super-resolution. This feature enhances details and improves image resolution to achieve high-definition processing while enlarging the image.

The value must be in the range of 1 to 4. Default value: 1. If you set upscale_factor to 1, only high-definition processing is performed on the image without magnification.

Line art to image

n integer (Optional)

The number of images to generate. Valid values: 1 to 4. Default value: 1.

seed integer (Optional)

The random number seed, which is used to control the randomness of the content generated by the model. The value of the seed parameter must be in the range of [0, 2147483647].

If you do not provide this parameter, the algorithm automatically generates a random number as the seed. To generate relatively stable content, use the same seed parameter value.

watermark bool (Optional)

Specifies whether to add a watermark. The watermark is located in the lower-right corner of the image, saying "AI Generated".

  • false (default)

  • true

is_sketch bool (Optional)

Specify this parameter only when function is set to doodle (line art to image).

Specifies whether the input image is a line art image.

  • false: The default value. The input image is not a line art image. The model first extracts the line art from the input image and then generates a new image based on the extracted art.

  • true: The input image is a line art image. The model generates an image directly from the input image. This is suitable for doodling scenarios.

Response parameters

Successful response

Save the task_id to query the task status and result.

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

Error response

The task creation failed. For more information, see Error messages to resolve the issue.

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"fb53c4ec-1c12-4fc4-a580-xxxxxx"
}

output object

The output information of the task.

Properties

task_id string

The task ID. The query is valid for 24 hours.

task_status string

The task status.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN

request_id string

The unique request ID. You can use this ID to trace and troubleshoot issues.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

Step 2: Query the result by task ID

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

Request parameters

Query task result

Replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task ID.

The API keys for the Singapore and Beijing regions are different. Obtain an API key.
The following code provides the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Request headers

Authorization string (Required)

The identity authentication credentials for the request. This API uses an Model Studio API key for identity authentication. Example: Bearer sk-xxxx.

Path parameters

task_id string (Required)

The task ID.

Response parameters

Successful task execution

Task data, such as the task status and image URLs, is retained for only 24 hours and is automatically purged after this period. You must save the generated images promptly.

{
    "request_id": "eeef0935-02e9-9742-bb55-xxxxxx",
    "output": {
        "task_id": "a425c46f-dc0a-400f-879e-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-02-21 17:56:31.786",
        "scheduled_time": "2025-02-21 17:56:31.821",
        "end_time": "2025-02-21 17:56:42.530",
        "results": [
            {
                "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/aaa.png"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Failed task execution

If a task fails, task_status is set to FAILED, and an error code and message are provided. For more information, see Error messages to resolve the issue.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "xxxxxx",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

Partially failed task

The model can generate multiple images in a single task. If at least one image is generated successfully, the task status is marked as SUCCEEDED, and the corresponding image URL is returned. For images that fail to generate, the result contains the reason for the failure. In addition, only successful results are counted in usage statistics. For more information, see Error messages to resolve the issue.

{
    "request_id": "85eaba38-0185-99d7-8d16-xxxxxx",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "code": "InternalError.Timeout",
                "message": "An internal timeout error has occured during execution, please try again later or contact service support."
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 1,
            "FAILED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

output object

The output information of the task.

Properties

task_id string

The task ID. The query is valid for 24 hours.

task_status string

The task status.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN

submit_time string

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

scheduled_time string

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

end_time string

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

results array object

The list of task results, including image URLs and error messages for partially failed tasks.

Data structure

{
    "results": [
        {
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}

task_metrics object

The task result statistics.

Properties

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of successful tasks.

FAILED integer

The number of failed tasks.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

usage object

The usage statistics for the request. Only successfully generated images are counted.

Properties

image_count integer

The number of images successfully generated by the model. Billing formula: Fee = Number of images × Unit price.

request_id string

The unique request ID. You can use this ID to trace and troubleshoot issues.

DashScope SDK

Make sure that you have installed the latest version of DashScope SDK. Otherwise, an error may occur.

The DashScope SDK is available in Python and Java.

The parameter names in the SDK are mostly the same as those in the HTTP API. The parameter structure is specific to the SDK encapsulation for each language. For more information about the parameters, see HTTP call.

Because image models require a long processing time, the underlying service is asynchronous. The SDK provides an encapsulation layer that supports both synchronous and asynchronous calls.

The general image editing model requires approximately 5 to 15 seconds to process a request. The actual processing time depends on the number of tasks in the queue and the network conditions.

Python SDK

When you use the Python SDK to process image files, you can use one of the following three methods to input an image. Select the method that best fits your scenario.

  1. Public URL: A publicly accessible image URL that uses the HTTP or HTTPS protocol.

  2. Base64 encoding: The Base64-encoded file string in the format of data:{MIME_type};base64,{base64_data}.

  3. Local file path: Supports both absolute and relative paths. For information about how to provide the correct file path, see the following table.

System

File path to be provided

Example (absolute path)

Example (relative path)

Linux or macOS

file://{absolute or relative path of the file}

file:///home/images/test.png

file://./images/test.png

Windows

file://D:/images/test.png

file://./images/test.png

Sample code

Note

Before you call the code, ensure that you have installed the DashScope Python SDK. We recommend that you upgrade to the latest version by running pip install -U dashscope. For more information, see Install the SDK.

Synchronous call

This example shows how to make a synchronous call and supports three image input methods: public URL, Base64 encoding, and local file path.

Sample request
import base64
import os
from http import HTTPStatus
from dashscope import ImageSynthesis
import mimetypes

"""
Environment requirements:
    dashscope python SDK >= 1.23.8
Install/Upgrade the SDK:
    pip install -U dashscope
"""

# If you have not configured environment variables, replace the following line with your Model Studio API key: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")


# --- Helper function: for Base64 encoding ---
# Format: 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("Unsupported or unrecognizable image format")
    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}"

"""
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. Use a local file - suitable for local development and testing.
3. Use Base64 encoding - suitable for private images or scenarios that require encrypted transmission.
"""

# [Method 1] Use a public image URL
mask_image_url = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3_mask.png"
base_image_url = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3.jpeg"

# [Method 2] Use a local file (absolute and relative paths are supported)
# Format requirement: file:// + file path
# Example (absolute path):
# mask_image_url = "file://" + "/path/to/your/mask_image.png"     # Linux/macOS
# base_image_url = "file://" + "C:/path/to/your/base_image.jpeg"  # Windows
# Example (relative path):
# mask_image_url = "file://" + "./mask_image.png"                 # Subject to the actual path
# base_image_url = "file://" + "./base_image.jpeg"                # Subject to the actual path

# [Method 3] Use a Base64-encoded image
# mask_image_url = encode_file("./mask_image.png")               # Subject to the actual path
# base_image_url = encode_file("./base_image.jpeg")              # Subject to the actual path


def sample_sync_call_imageedit():
    print('please wait...')
    rsp = ImageSynthesis.call(api_key=api_key,
                              model="wanx2.1-imageedit",
                              function="description_edit_with_mask",
                              prompt="A ceramic rabbit holding a ceramic flower",
                              mask_image_url=mask_image_url,
                              base_image_url=base_image_url,
                              n=1)
    assert rsp.status_code == HTTPStatus.OK

    print('response: %s' % rsp)
    if rsp.status_code == HTTPStatus.OK:
        for result in rsp.output.results:
            print("---------------------------")
            print(result.url)
    else:
        print('sync_call Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    sample_sync_call_imageedit()
Sample response
The URL is valid for 24 hours. Download the image promptly.
{
    "status_code": 200,
    "request_id": "dc41682c-4e4a-9010-bc6f-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "6e319d88-a07a-420c-9493-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com/xxx.png?xxxxxx"
            }
        ],
        "submit_time": "2025-05-26 14:58:27.320",
        "scheduled_time": "2025-05-26 14:58:27.339",
        "end_time": "2025-05-26 14:58:39.170",
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous invocation

This example shows only how to make an asynchronous call.

Sample request
import os
from http import HTTPStatus
from dashscope import ImageSynthesis

"""
Environment requirements:
    dashscope python SDK >= 1.23.4
Install/Upgrade the SDK:
    pip install -U dashscope
"""

# If you have not configured environment variables, replace the following line with your Model Studio API key: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")

# Use a public image URL
mask_image_url = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3_mask.png"
base_image_url = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3.jpeg"


def sample_async_call_imageedit():
    # Asynchronous call, returns a task_id
    rsp = ImageSynthesis.async_call(api_key=api_key,
                                    model="wanx2.1-imageedit",
                                    function="description_edit_with_mask",
                                    prompt="A ceramic rabbit holding a ceramic flower",
                                    mask_image_url=mask_image_url,
                                    base_image_url=base_image_url,
                                    n=1)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print("task_id: %s" % rsp.output.task_id)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))

    # Obtain asynchronous task information
    status = ImageSynthesis.fetch(rsp)
    if status.status_code == HTTPStatus.OK:
        print(status.output.task_status)  # check the task status
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (status.status_code, status.code, status.message))

    # Wait for the asynchronous task to finish
    rsp = ImageSynthesis.wait(rsp)
    print(rsp)
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
        for result in rsp.output.results:
            print("---------------------------")
            print(result.url)
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


if __name__ == '__main__':
    sample_async_call_imageedit()
Sample response

1. Example response for creating a task

{
	"status_code": 200,
	"request_id": "6dc3bf6c-be18-9268-9c27-xxxxxx",
	"code": "",
	"message": "",
	"output": {
		"task_id": "686391d9-7ecf-4290-a8e9-xxxxxx",
		"task_status": "PENDING",
		"video_url": ""
	},
	"usage": null
}

2. Example response for querying a task result

The URL is valid for 24 hours. Download the image promptly.
{
    "status_code": 200,
    "request_id": "dc41682c-4e4a-9010-bc6f-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "6e319d88-a07a-420c-9493-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com/xxx.png?Expires=17xxxxxx"
            }
        ],
        "submit_time": "2025-05-26 14:58:27.320",
        "scheduled_time": "2025-05-26 14:58:27.339",
        "end_time": "2025-05-26 14:58:39.170",
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Java SDK

When you use the Java SDK to process image files, you can use one of the following three methods to input an image. Select the method that best fits your scenario.

  1. Public URL: A publicly accessible image URL that uses the HTTP or HTTPS protocol.

  2. Base64 encoding: The Base64-encoded file string in the format of data:{MIME_type};base64,{base64_data}.

  3. Local file path: Only absolute paths are supported. For information about how to provide the correct file path, see the following table.

System

File path to be provided

Example

Linux or macOS

file://{absolute path of the file}

file:///home/images/test.png

Windows

file:///{absolute path of the file}

file:///D:/images/test.png

Sample code

Note

Before you call the code, ensure that you have installed the DashScope Java SDK. We recommend that you upgrade to the latest version. For more information, see Install the SDK.

Synchronous call

This example shows how to make a synchronous call and supports three image input methods: public URL, Base64 encoding, and local file path.

Sample request
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Environment requirements
 *      dashscope java SDK >=2.20.9
 * Update Maven dependencies:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */
 
public class ImageEditSync {

    // If you have not configured environment variables, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * Description of image input methods: Select one of the three methods
     *
     * 1. Use a public URL - suitable for publicly accessible images.
     * 2. Use a local file - suitable for local development and testing.
     * 3. Use Base64 encoding - suitable for private images or scenarios that require encrypted transmission.
     */

    //[Method 1] Public URL
    static String maskImageUrl = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3_mask.png";
    static String baseImageUrl = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3.jpeg";

    //[Method 2] Local file path (file://+absolute path or file:///+absolute path)
    // static String maskImageUrl = "file://" + "/your/path/to/mask_image.png";    // Linux/macOS
    // static String baseImageUrl = "file:///" + "C:/your/path/to/base_image.png";  // Windows

    //[Method 3] Base64 encoding
    // static String maskImageUrl = encodeFile("/your/path/to/mask_image.png");
    // static String baseImageUrl = encodeFile("/your/path/to/base_image.png");


    public static void syncCall() {
        // Set the parameters parameter
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wanx2.1-imageedit")
                        .function(ImageSynthesis.ImageEditFunction.DESCRIPTION_EDIT_WITH_MASK)
                        .prompt("A ceramic rabbit holding a ceramic flower")
                        .maskImageUrl(maskImageUrl)
                        .baseImageUrl(baseImageUrl)
                        .n(1)
                        .size("1024*1024")
                        .parameters(parameters)
                        .build();

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

    /**
     * Encode a file into a Base64 string
     * @param filePath File path
     * @return Base64 string in the format of data:{MIME_type};base64,{base64_data}
     */
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("File does not exist: " + filePath);
        }
        // Detect the MIME type
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot detect the file type: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("Unsupported or unrecognizable image format");
        }
        // Read the file content and encode it
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read the file content: " + filePath);
        }

        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void main(String[] args) {
        syncCall();
    }
}
Sample response
The URL is valid for 24 hours. Download the image promptly.
{
    "request_id": "bf6c6361-f0fc-949c-9d60-xxxxxx",
    "output": {
        "task_id": "958db858-153b-4c81-b243-xxxxxx",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com/xxx.png?xxxxxx"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous invocation

This example shows only how to make an asynchronous call.

Sample request
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Environment requirements
 *      dashscope java SDK >= 2.20.1
 * Update Maven dependencies:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */
 
public class ImageEditAsync {

    // If you have not configured environment variables, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    //[Method 1] Public URL
    static String maskImageUrl = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3_mask.png";
    static String baseImageUrl = "http://wanx.alicdn.com/material/20250318/description_edit_with_mask_3.jpeg";

    public static void asyncCall() {
        // Set the parameters parameter
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wanx2.1-imageedit")
                        .function(ImageSynthesis.ImageEditFunction.DESCRIPTION_EDIT_WITH_MASK)
                        .prompt("A ceramic rabbit holding a ceramic flower")
                        .maskImageUrl(maskImageUrl)
                        .baseImageUrl(baseImageUrl)
                        .n(1)
                        .size("1024*1024")
                        .parameters(parameters)
                        .build();
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---async call, please wait a moment----");
            result = imageSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();

        System.out.println("taskId=" + taskId);


        try {
            result = imageSynthesis.wait(taskId, apiKey);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        System.out.println(JsonUtils.toJson(result.getOutput()));
    }

    public static void listTask() throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        ImageSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    public void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        // If DASHSCOPE_API_KEY is set as an environment variable, apiKey can be empty.
        ImageSynthesisResult result = is.fetch(taskId, null);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }


    public static void main(String[] args) {
        asyncCall();
    }
}
Sample response

1. Example response for creating a task

{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}

2. Example response for querying a task result

The video_url expires in 24 hours. Please download the video promptly.
{
	"request_id": "3d740fc4-a968-9c36-b0e7-xxxxxxxx",
	"output": {
		"task_id": "34dcf4b0-ed84-441e-91cb-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"video_url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/aaaa.mp4"
	},
	"usage": {
		"video_count": 1,
		"video_duration": 5,
		"video_ratio": "standard"
	}
}

Error codes

If a call fails, see Error messages for troubleshooting.

This API also returns the following specific error codes.

HTTP status code

code (API error code)

API error message (message)

Description

400

InvalidParameter

InvalidParameter

The request parameters are invalid.

400

IPInfringementSuspect

Input data is suspected of being involved in IP infringement.

The input data (such as the prompt or image) is suspected of intellectual property infringement. Check the input to make sure that it does not contain content that may cause infringement risks.

400

DataInspectionFailed

Input data may contain inappropriate content.

The input data (such as the prompt or image) may contain inappropriate content. Modify the input and try again.

500

InternalError

InternalError

A service error occurred. Try again to rule out accidental occurrences.

Input image description

Pass by value

The input image can be provided in multiple string formats. The following table describes the supported formats for each call method.

Method

HTTP

Python SDK

Java SDK

Supported input image methods

  • Public URL

  • Base64 encoding

  • Public URL

  • Base64 encoding

  • Local file path

  • Public URL

  • Base64 encoding

  • Local file path

Method 1: Use a public URL

  • Provide a publicly accessible image URL. Both HTTP and HTTPS are supported.

  • Example: https://xxxx/img.png.

Method 2: Use Base64 encoding

Convert a local image file to a Base64-encoded string and provide it in the format of data:{MIME_type};base64,{base64_data}.

  • For the conversion code, see Sample code.

  • {MIME_type}: The media type of the image. This must correspond to the file format.

  • {base64_data}: The Base64-encoded image data.

  • MIME type mapping:

    Image format

    MIME type

    JPEG

    image/jpeg

    JPG

    image/jpeg

    PNG

    image/png

    BMP

    image/bmp

    TIFF

    image/tiff

    WEBP

    image/webp

  • Example: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDg......".

    Note: The preceding Base64 string is truncated for demonstration purposes. In practice, you must pass the complete encoded string.

Method 3: Use a local file path

  • HTTP calls do not support local file paths. This method is supported only by the Python and Java SDKs.

  • For more information about the rules for passing local file paths, see Python SDK and Java SDK.

Image access configuration

Configure a domain name whitelist: Ensure your business system can access image links

Generated images are stored in Alibaba Cloud OSS. Each image is assigned an OSS link, such as https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png. OSS links allow public access, and you can use them to view or download the image. The link is valid for only 24 hours.

If your business has high security requirements and cannot access Alibaba Cloud OSS links, you must configure a whitelist for public access. Add the following domain names to your whitelist to access the image links.

# OSS domain name list
dashscope-result-bj.oss-cn-beijing.aliyuncs.com
dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com
dashscope-result-sh.oss-cn-shanghai.aliyuncs.com
dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com
dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com
dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com
dashscope-result-hy.oss-cn-heyuan.aliyuncs.com
dashscope-result-cd.oss-cn-chengdu.aliyuncs.com
dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com
dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com

FAQ

For general questions about image models, see the FAQ document. This document covers topics such as model billing, request limits, and solutions to common API errors.