Wan2.1 - general image editing API reference

Updated at:

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

ImportantThis document applies only to the China (Beijing) region. Use an API key from this region.

ImportantAlibaba Cloud Model Studio provides a workspace-specific domain for the China (Beijing) region: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com, which delivers superior performance and higher stability for inference requests. We recommend that you migrate from https://dashscope.aliyuncs.com to the new domain.

{WorkspaceId} is your workspace ID. You can view it on the Workspace details page in the Model Studio console. The existing domain remains available.

This model uses simple instructions to perform various image editing tasks (image expansion, watermark removal, style transfer, image inpainting, and image enhancement). The following features are currently supported:

  • Image stylization: Global and local stylization.
  • Image content editing: Instruction-based editing (add or modify image content using instructions without specifying a region), inpainting (add, delete, or modify content in a specified area), and text watermark removal (Chinese and English).
  • Image size and resolution optimization: Image expansion (expand by ratio) and super resolution (enhance to high definition).
  • Image color processing: Colorization (convert black-and-white or grayscale images to color).
  • Generation based on a reference image: Sketch-to-image generation (extract a sketch from the input image and then generate an image based on the sketch) and cartoon character reference generation.

Related guide: Image editing - Wan2.1

Model effects

Feature

Input image

Input prompt

Output image

Global stylization

image

Convert to French picture book style

image

Local stylization

image

Transform the house into a wooden plank style.

image

Instruction-based editing

image

Change her hair color to red.

image

Inpainting

Input image

image

Input mask image (white indicates the masked area)

image

A ceramic rabbit holding a ceramic flower.

Output image

image

Text and watermark removal

image

Remove text from the image.

image

Outpainting

20250319105917

A green fairy.

image

Image super-resolution

Blurred image

image

Image super-resolution.

Clear image

image

Image colorization

image

A blue background with yellow leaves.

image

Sketch-to-image

Input image

image

A living room in Scandinavian minimalist style.

Extract the sketch lines from the original image and generate an image

image

Reference cartoon character for image generation

Input reference image (cartoon character)

image

The cartoon character cautiously pokes its head out, peeking at a brilliant blue gemstone in the room.

Output image

image

Prerequisites

The Wanx-omni image editing API supports calls via HTTP and the DashScope SDK.

Before calling the API, you need to obtain and configure an API Key, and then configure the API Key in environment variables.

To call the API through the SDK, please install the DashScope SDK. Currently, the SDK supports Python and Java.

HTTP calls

Image models take a long time to process. To avoid request timeouts, HTTP calls only support retrieving model results asynchronously. You need to make two requests:

  1. Create a task to get the task ID: First, send a task creation request, which returns a task ID (task_id).
  2. Query the result by task ID: Use the task ID obtained in the previous step to query the task status and result. When the task succeeds, the image URL is returned, valid for 24 hours.

NoteAfter you create a task, it is added to a queue and waits to be scheduled. You then need to call the "query the result by task ID" API to get the task status and result.

The general image editing model takes about 5 to 15 seconds to process a request. The actual time depends on the number of tasks in the queue and the network conditions. Please wait patiently for the result.

Step 1: Create a task to get the task ID

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

Replace {WorkspaceId} with your actual workspace ID.

Request parameters

Request headers

Content-Typestring(Required)

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

Authorization string (Required)

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

X-DashScope-Asyncstring(Required)

Asynchronous processing configuration parameter. HTTP requests only support asynchronous mode, so it must be set toenable.

ImportantIf this request header is missing, an error occurs: "current user api does not support synchronous calls".

Request body

model string (Required)

Model name. Example value: wanx2.1-imageedit.

input object (Required)

Basic input information, such as the prompt.

Properties

promptstring(Required)

The prompt used to describe the elements and visual features that you want in the generated image.

Both Chinese and English are supported. The length must not exceed 800 characters, with each Chinese character or letter counting as one character. Any excess is automatically truncated.

Prompts vary by function. We recommend that you refer to the prompt techniques for the specific function you are using.

functionstring(Required)

Image editing function. Currently supported functions:

  • stylization_all: global stylization, currently supporting 2 styles. Styles and prompt tips
  • stylization_local: local stylization, currently supporting 8 styles. Styles and prompt tips
  • description_edit: instruction-based editing. You can edit an image simply by using an instruction; this method is recommended first for simple editing tasks. Prompt tips
  • description_edit_with_mask: local repainting. You must specify the region to edit, which is suitable for scenarios that require precise control over the edit scope. Prompt tips
  • remove_watermark: remove text watermarks. Prompt tips
  • expand: outpainting. Prompt tips
  • super_resolution: image super-resolution. Prompt tips
  • colorization: image colorization. Prompt tips
  • doodle: sketch-to-image. Prompt tips
  • control_cartoon_feature: generate images from a reference cartoon character. Prompt tips

base_image_url string (Required)

URL or Base64-encoded data of the input image.

Image restrictions:

  • Image formats: JPG, JPEG, PNG, BMP, TIFF, WEBP.
  • Image resolution: the image width and height range from [512, 4096] pixels.
  • Image size: no more than 10MB.
  • The URL must not contain Chinese characters.

Input image notes:

  1. Use a publicly accessible URL

    • Supports the HTTP or HTTPS protocol. You can also get a temporary public URL here.
    • Example value: http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg.
  2. The string obtained by encoding the image in Base64

    • Data format: data:{MIME_type};base64,{base64_data}.
    • Example value: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ.......
    • The encoded string in the example is incomplete and is for demonstration only. For more information, see value passing methods.

mask_image_url string (optional)

Required only when function is set to description_edit_with_mask (partial repaint). In other cases, this parameter is not required.

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

Supports public-accessible URLs (HTTP/HTTPS) or Base64-encoded strings. For more information, see value passing methods.

Requirements for the mask area image:

  • Image resolution: Must be consistent with the image resolution of base_image_url. The image width and height must be within [512, 4096] pixels.
  • Image format: JPG, JPEG, PNG, BMP, TIFF, and WEBP are supported.
  • Image size: No more than 10MB.
  • The URL must not contain Chinese characters.

Requirements for mask area colors:

  • White area: Represents the part to be edited. It must be pure white (RGB value [255,255,255]), otherwise it may not be recognized correctly.
  • Black area: Represents the part that does not need to be changed. It must be pure black (RGB value [0,0,0]), otherwise it may not be recognized correctly.

How to obtain the mask area image: use Photoshop to cut out the area, or use other tools to generate a black-and-white mask image.

parameters object (optional)

Image processing parameters.

Properties

General

n integer (optional)

The number of images to generate. Range: 1~4. Default: 1.

seedinteger (optional)

The random number seed used to control the randomness of the generated content. Value range: [0, 2147483647]. If not specified, it is automatically generated; using the same value keeps the results stable.

watermark bool (optional)

Whether to add the watermark. The watermark is located in the lower-right corner of the image, with the text "AI Generated".

  • false: The default value. No watermark is added.
  • true: The watermark is added.

Global stylization

n、seed、watermark

For descriptions, see General parameters.

strength float (optional)

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

The magnitude of image modification. Range: [0.0, 1.0]. Default: 0.5.

The closer the value is to 0, the closer the result is to the original image; the closer the value is to 1, the greater the modification to the original image.

Instruction-based editing

n、seed、watermark

For descriptions, see General parameters.

strength float (optional)

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

The magnitude of image modification. Range: [0.0, 1.0]. Default: 0.5.

The closer the value is to 0, the closer the result is to the original image; the closer the value is to 1, the greater the modification to the original image.

Outpainting

n、seed、watermark

For descriptions, see General parameters.

top_scale float (Optional)

Required only when function is set to expand (outpainting).

Upward expansion ratio. The default value is 1.0. Value range: [1.0, 2.0].

bottom_scale float (Optional)

Required only when function is set to expand (outpainting).

Downward expansion ratio. The default value is 1.0. Value range: [1.0, 2.0].

left_scale float (Optional)

Required only when function is set to expand (outpainting).

Leftward expansion ratio. The default value is 1.0. Value range: [1.0, 2.0].

right_scale float (Optional)

Required only when function is set to expand (outpainting).

Rightward expansion ratio. The default value is 1.0. Value range: [1.0, 2.0].

Image super resolution

n、seed、watermark

For descriptions, see General parameters.

upscale_factor integer (Optional)

Required only when function is set to super_resolution (image super resolution).

The upscale factor for image super resolution. It enhances details while upscaling the image, improves image resolution, and delivers HD processing.

Value range: 1~4. Default value: 1. When it is set to 1, only HD processing is performed without upscaling.

Sketch to image

n、seed、watermark

For descriptions, see General parameters.

is_sketch bool (Optional)

Required only when function is set to doodle (sketch to image).

Whether the input image is a sketch image.

  • false: The default value. The input image is not a sketch image. The model first extracts a sketch from the input image, and then generates a new image with reference to the extracted sketch.
  • true: The input image is a sketch image. The model directly generates an image based on the input image, which is suitable for doodle-to-image scenarios.

Global stylization

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "转换成法国绘本风格",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg"
  },
  "parameters": {
    "n": 1
  }
}'

Pass in a local file (base64)

The following uses global stylization as an example to show how to pass parameters in Base64.

Since the Base64-encoded string is long, download image_base64 and copy the entire text content to the base_image_url parameter.

For more information about data formats, see Value passing methods.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "转换成法国绘本风格",
    "base_image_url": "data:image/jpeg;base64,/9j/4AAQSkZJR......"
  },
  "parameters": {
    "n": 1
  }
}'

Partial stylization

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "把房子变成木板风格。",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/stylization_local_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Instruction-based editing

No need to specify a region. You can add or modify image content through instructions.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "把她的头发修改为红色。",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/description_edit_2.png"
  },
  "parameters": {
    "n": 1
  }
}'

Partial repainting

For a specified region, you can add, delete, or modify image content.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "陶瓷兔子拿着陶瓷小花。",
    "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
  }
}'

Remove text watermarks

Can remove text watermarks in Chinese and English.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "去除图像中的文字",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/remove_watermark_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Outpainting

Supports proportional outpainting in four directions: up, down, left, and right.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "一位绿色仙子",
    "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

Supports high-definition upscaling of blurry images.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "图像超分。",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/super_resolution_1.jpeg"
  },
  "parameters": {
    "upscale_factor": 2,
    "n": 1
  }
}'

Image colorization

Supports converting black-and-white or grayscale images to color images.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "蓝色背景,黄色的叶子。",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/colorization_1.jpeg"
  },
  "parameters": {
    "n": 1
  }
}'

Sketch to image

First extracts the line art of the input image, then generates an image based on that line art.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "北欧极简风格的客厅。",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/doodle_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Image generation based on cartoon characters

Supports generating images based on cartoon characters.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "卡通形象小心翼翼地探出头,窥视着房间内一颗璀璨的蓝色宝石。",
    "base_image_url": "http://wanx.alicdn.com/material/20250318/control_cartoon_feature_1.png"
  },
  "parameters": {
    "n": 1
  }
}'

Response parameters

output object

The task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING: The task is in the queue.
  • RUNNING: The task is being processed.
  • SUCCEEDED: The task is executed successfully.
  • FAILED: The task failed.
  • CANCELED: The task is canceled.
  • UNKNOWN: The task does not exist or its status is unknown.

request_idstring

Unique request identifier for tracing and troubleshooting.

codestring

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

messagestring

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

Successful response

Please save the task_id for querying the task status and results.

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

Error response

Task creation failed. See Error codes.

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

Step 2: Query result by task ID

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

Replace {WorkspaceId} with your actual workspace ID.

Request parameters

Request 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.

Query task result

Please replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task_id.

curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

outputobject

The task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING: The task is in the queue.
  • RUNNING: The task is being processed.
  • SUCCEEDED: The task is executed successfully.
  • FAILED: The task failed.
  • CANCELED: The task is canceled.
  • UNKNOWN: The task does not exist or its status is unknown.

submit_time string

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

scheduled_time string

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

end_time string

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

results array object

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

Data structure

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

task_metrics object

Statistics for the task result.

Properties

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of successful tasks.

FAILED integer

The number of failed tasks.

codestring

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

messagestring

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

usage object

The output information statistics. Only successful results are counted.

Properties

image_count integer

Number of images successfully generated. Billing: Cost = Number of images × Unit price.

request_idstring

Unique request identifier for tracing and troubleshooting.

Task successful

Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save 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
    }
}

Task failed

If the task fails to execute, task_status will be set to FAILED, and an error code and message will be provided. See Error codes for troubleshooting.

{
    "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
        }
    }
}

Task partially failed

The model can generate multiple images per task. If at least one succeeds, the task status is SUCCEEDED and URLs of successful images are returned. Failed images include a failure reason. Usage statistics count only successful results. See Error codes.

{
    "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
    }
}

DashScope SDK

First, ensure you have installed the latest version of the DashScope SDK. Otherwise, a runtime error may occur.

The DashScope SDK currently supports Python and Java.

The parameter names in the SDK are mostly consistent with those in the HTTP API. The parameter structure depends on the SDK encapsulation for different languages. For parameter descriptions, see HTTP call.

Video model processing takes a long time, so the service uses an asynchronous approach. The SDK provides a wrapper supporting both synchronous and asynchronous calls.

The general image editing model takes about 5 to 15 seconds to process a request. The actual time depends on the number of tasks in the queue and the network conditions. Please wait patiently for the result.

Python SDK

ImportantThis example requires dashscope Python SDK ≥ 2.0.1. Run pip install -U "dashscope>=2.0.1" to upgrade the SDK before running the example.

When using the Python SDK to process image files, input an image using one of the following three methods. Choose the method that best fits your scenario.

  1. Public URL: A publicly accessible image URL that uses the HTTP or HTTPS protocol. You can obtain a temporary public URL.
  2. Base64-encoded: Pass the Base64-encoded file string in the data:{MIME_type};base64,{base64_data} format.
  3. Local file path: Supports both absolute and relative paths. See the following table for valid file path formats.

System

File path to pass

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

NoteBefore calling the code, install or upgrade the DashScope Python SDK to the latest version: pip install -U dashscope. See Install the SDK.

Synchronous call

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

Request example
import base64
import os
import mimetypes
import dashscope
from dashscope import DashScopeError

"""
环境要求:
    dashscope python SDK >= 2.0.1
安装/升级SDK:
    pip install -U dashscope
"""

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

# --- 辅助函数:用于 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
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"

# 【方式二】使用本地文件(支持绝对路径和相对路径)
# 格式要求:file:// + 文件路径
# 示例(绝对路径):
# mask_image_url = "file://" + "/path/to/your/mask_image.png"     # Linux/macOS
# base_image_url = "file://" + "C:/path/to/your/base_image.jpeg"  # Windows
# 示例(相对路径):
# mask_image_url = "file://" + "./mask_image.png"                 # 以实际路径为准
# base_image_url = "file://" + "./base_image.jpeg"                # 以实际路径为准

# 【方式三】使用Base64编码的图片
# mask_image_url = encode_file("./mask_image.png")               # 以实际路径为准
# base_image_url = encode_file("./base_image.jpeg")              # 以实际路径为准

def sample_sync_call_imageedit():
    print('please wait...')
    try:
        # generate 为“提交+等待”一步式调用,返回已完成的任务对象 job
        job = client.images.generate(
            model="wanx2.1-imageedit",
            function="description_edit_with_mask",
            prompt="陶瓷兔子拿着陶瓷小花",
            # base_image_url/mask_image_url 为编辑专属入参,经 extra_input 透传到请求 input 段
            extra_input={
                "mask_image_url": mask_image_url,
                "base_image_url": base_image_url,
            },
            n=1,
        )
        print('response: %s' % job)
        for url in job.image_urls:
            print("---------------------------")
            print(url)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    sample_sync_call_imageedit()
Response example

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

{
    "request_id": "dc41682c-4e4a-9010-bc6f-xxxxxx",
    "task_id": "6e319d88-a07a-420c-9493-xxxxxx",
    "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 call

This example shows only the asynchronous call method.

Request example
import os
import dashscope
from dashscope import DashScopeError

"""
环境要求:
    dashscope python SDK >= 2.0.1
安装/升级SDK:
    pip install -U dashscope
"""

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

# 使用公网图片 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():
    try:
        # 异步调用(分步提交),返回一个job对象,含task_id
        job = client.images.jobs.create(
            model="wanx2.1-imageedit",
            function="description_edit_with_mask",
            prompt="陶瓷兔子拿着陶瓷小花",
            # base_image_url/mask_image_url 为编辑专属入参,经 extra_input 透传到请求 input 段
            extra_input={
                "mask_image_url": mask_image_url,
                "base_image_url": base_image_url,
            },
            n=1,
        )
        print(job)
        print("task_id: %s" % job.task_id)

        # 获取异步任务信息
        snapshot = client.images.jobs.fetch(job.task_id)
        print(snapshot.status)  # check the task status

        # 等待异步任务结束(指数退避轮询,默认总预算24小时,任务FAILED会抛出DashScopeError)
        done = client.images.jobs.wait(job.task_id)
        print(done)
        for url in done.image_urls:
            print("---------------------------")
            print(url)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    sample_async_call_imageedit()
Response example
  1. Response example for creating a task
{
    "request_id": "6dc3bf6c-be18-9268-9c27-xxxxxx",
    "task_id": "686391d9-7ecf-4290-a8e9-xxxxxx",
    "status": "PENDING"
}
  1. Response example for querying a task result

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

{
    "request_id": "dc41682c-4e4a-9010-bc6f-xxxxxx",
    "task_id": "6e319d88-a07a-420c-9493-xxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com/xxx.png?Expires=17xxxxxx"
        }
    ],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "image_count": 1
    }
}

Java SDK

When using the Java SDK to process image files, input an image using one of the following three methods. Choose the method that best fits your scenario.

  1. Public URL: A publicly accessible image URL that uses the HTTP or HTTPS protocol. You can obtain a temporary public URL.
  2. Base64-encoded: Pass the Base64-encoded file string in the data:{MIME_type};base64,{base64_data} format.
  3. Local file path: Only absolute paths are supported. See the following table for valid file path formats.

System

File path to pass

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

NoteBefore calling the code, install or upgrade the DashScope Java SDK to the latest version. See Install the SDK.

Synchronous call

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

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

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

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;

/**
 * 环境要求
 *      dashscope java SDK >=2.20.9
 * 更新maven依赖:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */

public class ImageEditSync {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * 图像输入方式说明:三选一即可
     *
     * 1. 使用公网URL - 适合已有公开可访问的图片
     * 2. 使用本地文件 - 适合本地开发测试
     * 3. 使用Base64编码 - 适合私有图片或需要加密传输的场景
     */

    //【方式一】公网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";

    //【方式二】本地文件路径(file://+绝对路径 or file:///+绝对路径)
    // static String maskImageUrl = "file://" + "/your/path/to/mask_image.png";    // Linux/macOS
    // static String baseImageUrl = "file:///" + "C:/your/path/to/base_image.png";  // Windows

    //【方式三】Base64编码
    // static String maskImageUrl = encodeFile("/your/path/to/mask_image.png");
    // static String baseImageUrl = encodeFile("/your/path/to/base_image.png");

    public static void syncCall() {
        // 设置parameters参数
        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("陶瓷兔子拿着陶瓷小花")
                        .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));
    }

    /**
     * 将文件编码为Base64字符串
     * @param filePath 文件路径
     * @return Base64字符串,格式为 data:{MIME_type};base64,{base64_data}
     */
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("文件不存在: " + filePath);
        }
        // 检测MIME类型
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法检测文件类型: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("不支持或无法识别的图像格式");
        }
        // 读取文件内容并编码
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法读取文件内容: " + filePath);
        }

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

    public static void main(String[] args) {
        syncCall();
    }
}
Response example

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 call

This example shows only the asynchronous call method.

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

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

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

/**
 * 环境要求
 *      dashscope java SDK >= 2.20.1
 * 更新maven依赖:
 *      https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
 */

public class ImageEditAsync {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey="sk-xxx"
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    //【方式一】公网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() {
        // 设置parameters参数
        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("陶瓷兔子拿着陶瓷小花")
                        .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();
        param.setApiKey(apiKey);
        ImageSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    public void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        // 如果已设置 DASHSCOPE_API_KEY 为环境变量,apiKey 可为空。
        ImageSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args) {
        asyncCall();
    }
}
Response example
  1. Response example for creating a task
{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}
  1. Response example for querying a task result

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

{
	"request_id": "3d740fc4-a968-9c36-b0e7-xxxxxxxx",
	"output": {
		"task_id": "34dcf4b0-ed84-441e-91cb-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [
			{
				"url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxx.png"
			}
		],
		"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",
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Error codes

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

This API also has specific status codes, as shown in the following table.

HTTP status code

API error code (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 ensure it does not contain content that poses an infringement risk.

400

DataInspectionFailed

Input data may contain inappropriate content.

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

500

InternalError

InternalError

The service is abnormal. Try again to rule out an occasional issue.

Input image formats

Supported formats

Input images support multiple string formats, as shown in the following table.

Invocation 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 public URL
  • Provide a publicly accessible image address. HTTP or HTTPS protocols are supported. You can get a temporary public URL here.
  • Example: https://xxxx/img.png
Method 2: Use Base64 encoding

Convert a local image file to a Base64 string and concatenate it into the format data:{MIME_type};base64,{base64_data}.

  • For the conversion code, see Sample code

  • {MIME_type}: The media type of the image, which must match the file format

  • {base64_data}: The Base64-encoded string of the image file

  • MIME type reference:

    Image format

    MIME Type

    JPEG

    image/jpeg

    JPG

    image/jpeg

    PNG

    image/png

    BMP

    image/bmp

    TIFF

    image/tiff

    WEBP

    image/webp

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

    Note: The Base64 string above is truncated for demonstration. In actual use, pass the complete encoded string.

Method 3: Use local file path
  • HTTP does not support local file paths. Only the Python SDK and Java SDK support this method.
  • For local file path rules, see Python SDK and Java SDK.

FAQ

For common questions about image models, see the Image API FAQ. It includes the following: model billing and rate limit rules, solutions to frequent API errors, and more.