All Products
Search
Document Center

Alibaba Cloud Model Studio:Wanx-General Image Editing API Reference

Last Updated:Nov 24, 2026

This topic describes the input and output parameters of the Wanx-General Image Editing model.

ImportantThis document applies only to the China (Beijing) region. To use the model, you must use an API Key of the China (Beijing) region.

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

Among them, {WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains available.

This model enables diverse image edits with simple instructions and is suitable for scenarios such as outpainting, watermark removal, style transfer, image restoration, and image enhancement. The following features are currently supported:

  • Image stylization: global stylization and local stylization.
  • Image content editing: instruction-based editing (add or modify image content through instructions only, without specifying a region), inpainting (add, delete, or modify image content in a specified region), and text watermark removal (Chinese and English).
  • Image size and resolution optimization: outpainting (proportional outpainting) and image super-resolution (HD upscaling).
  • Image color processing: image colorization (converting black-and-white or grayscale images into color images).
  • Reference-image-based generation: line art to image (extract the line art of the input image first, and then generate an image based on the line art) and cartoon character reference to image.

Related guides: Image Editing-Wanx 2.1

Model overview

Model

Unit price

Rate limit (shared by the primary account and RAM sub-accounts)

RPS limit on the task submission API

Number of tasks being processed simultaneously

wanx2.1-imageedit

$0.020070/image

2

2

Model effects

Model feature

Input image

Input prompt

Output image

Global stylization

image

Convert to French picture book style

image

Local stylization

image

Turn the house into a wooden plank style.

image

Instruction-based editing

image

Change her hair to red.

image

Local repainting

Input image

image

Input image with the masked area (the white area indicates the mask)

image

A ceramic rabbit holding a ceramic flower.

Output image

image

Text watermark removal

image

Remove text from the image.

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 from the original image and generate an image

image

Generating images from a cartoon reference

Input reference image (cartoon character)

image

The cartoon character cautiously pokes its head out to peek at a sparkling blue gem in the room.

Output image

image

Prerequisites

The Wanx-general image editing API supports calls over HTTP and with DashScope SDKs.

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

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

Please replace DASHSCOPE_API_HOST in the sample code with the obtained API Host.

HTTP invocation

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

  1. Create a task to obtain 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 is executed successfully, the image URL is returned, which remains valid for 24 hours.

NoteAfter a task is created, it is added to a queue and waits to be scheduled for execution. You must then call the "Query task result by task ID" API to obtain the task status and result.

General image editing models take about 5 to 15 seconds. The actual time depends on the number of queued tasks and network conditions. Please be patient when obtaining the results.

Step 1: Create a task to obtain the task ID

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

When you make the call, replace {WorkspaceId} with the actual workspace ID.

Request parameters

Request headers

Content-Typestring(Required)

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

Authorizationstring(Required)

Request authentication. The API uses the Alibaba Cloud Bailian API Key for authentication. Example value: Bearer sk-xxxx.

X-DashScope-Asyncstring(Required)

Asynchronous processing configuration parameter. HTTP requests support only asynchronous calls and must be set to enable.

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

Request body

model string (Required)

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

input object (Required)

Basic input information, such as the prompt.

Property

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, with a length of no more than 800 characters. Each Chinese character or letter counts as one character, and any excess is automatically truncated.

Prompts differ between functions. We recommend that you refer to the prompt techniques for the specific function.

functionstring(Required)

The image editing function. Currently supported functions:

base_image_url string (Required)

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

Image limits:

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

Input image description:

  1. Use a publicly accessible URL

    • The HTTP or HTTPS protocol is supported.
    • Example value: http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg.
  2. Pass in a Base64-encoded image string

    • 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 (local repainting). In other cases, leave it unspecified.

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

You can pass in a publicly accessible URL (HTTP/HTTPS) or a Base64-encoded string. 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 the mask area colors:

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

To obtain a mask area image: use Photoshop to extract the subject or use other tools to generate a black-and-white mask image.

parameters object (Optional)

Image processing parameters.

Property

General

n integer (Optional)

The number of images to generate. Range 1~4, default 1.

seedinteger(Optional)

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

watermark bool (Optional)

Whether to add a 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: add a watermark.

Global stylization

n、seed、watermark

See General parameters for details.

strength float (Optional)

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

The extent 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

See General parameters for details.

strength float (Optional)

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

The extent 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.

Image expansion

n、seed、watermark

See General parameters for details.

top_scale float (Optional)

Required only when function is set to expand (image expansion).

Upward expansion ratio. Default: 1.0, range: [1.0, 2.0].

bottom_scale float (Optional)

Required only when function is set to expand (image expansion).

Downward expansion ratio. Default: 1.0, range: [1.0, 2.0].

left_scale float (Optional)

Required only when function is set to expand (image expansion).

Leftward expansion ratio. Default: 1.0, range: [1.0, 2.0].

right_scale float (Optional)

Required only when function is set to expand (image expansion).

Rightward expansion ratio. Default: 1.0, range: [1.0, 2.0].

Image super resolution

n、seed、watermark

See General parameters for details.

upscale_factor integer (Optional)

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

The magnification factor for image super resolution. It enhances details while enlarging the image and improves image resolution for HD processing.

Range: 1~4, default: 1. When it is set to 1, only HD processing is performed without magnification.

Sketch-to-image

n、seed、watermark

See General parameters for details.

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 based on 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 doodling 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 example uses global stylization to demonstrate how to pass parameters via Base64.

Since the Base64-encoded string is long, please download image_base64 and copy the entire text content into 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
  }
}'

Local 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 region needs to be specified. 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
  }
}'

Local repainting

You can add, delete, or modify image content in a specified region.

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

Text watermark removal

It can remove Chinese and English text watermarks.

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

Image expansion

Supports proportional image expansion in the up, down, left, and right directions.

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 upscaling blurry images to high definition.

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, and then generates an image based on the 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
  }
}'

Generate images 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

Task output information.

Property

task_id string

Task ID. The validity period for query is 24 hours.

task_status string

Task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is being processed
  • SUCCEEDED: The task executed successfully
  • FAILED: The task failed to execute
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or its status is unknown

request_idstring

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

codestring

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

messagestring

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

Success response

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

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

Error response

Failed to create the task. See Error codes for troubleshooting.

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

Step 2: Query results by task ID

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

When you make the call, replace {WorkspaceId} with the actual workspace ID.

Request parameters

Request headers

Authorizationstring(Required)

Request authentication. The API uses the Alibaba Cloud Bailian API Key for authentication. Example value: Bearer sk-xxxx.

URL path parameters

task_id string(Required)

Task ID.

Query task results

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

Task output information.

Property

task_id string

Task ID. The validity period for query is 24 hours.

task_status string

Task status.

Enumerated values

  • PENDING: The task is queuing
  • RUNNING: The task is being processed
  • SUCCEEDED: The task executed successfully
  • FAILED: The task failed to execute
  • CANCELED: The task has been canceled
  • UNKNOWN: The task does not exist or its status is unknown

submit_time string

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

scheduled_time string

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

end_time string

Task completion time. The time zone is UTC+8, and the format is YYYY-MM-DD HH:mm:ss.SSS.

results array object

The task result list, including image URLs and error messages about partially failed tasks.

Data structure

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

task_metrics object

Task result statistics.

Property

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of tasks whose task status is successful.

FAILED integer

The number of tasks whose task status is failed.

codestring

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

messagestring

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

usage object

Output information statistics. Only successful results are counted.

Property

image_count integer

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

request_idstring

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

Task execution succeeded

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

{
    "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 execution failed

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

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

Partial task failure

The model can generate multiple images in a single task. As long as one image is successfully generated, the task status is marked as SUCCEEDED, and the corresponding image URL is returned. For images that fail to be generated, the result contains the corresponding failure reason. In addition, only successful results are counted in the usage statistics. For more information, 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
    }
}

Call the DashScope SDK

Make sure that you have installed the latest version of the DashScope SDK first; otherwise, errors may occur during running.

The DashScope SDK currently supports Python and Java.

The parameter names of the SDK are basically the same as those of the HTTP API, and the parameter structure depends on the SDK encapsulation of each language. For parameter descriptions, see HTTP calls.

Because video model processing takes a long time, the underlying service is provided in an asynchronous manner. The SDK encapsulates this at the upper layer and supports both synchronous and asynchronous calls.

General image editing models take about 5 to 15 seconds. The actual time depends on the number of queued tasks and network conditions. Please be patient when obtaining the results.

Call the 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 you use the Python SDK to process image files, the following three methods are supported for entering images. Choose one based on your scenario.

  1. Public URL: a publicly accessible image URL (HTTP/HTTPS).
  2. Base64 encoding: a string obtained after the file is Base64-encoded, in the format of data:{MIME_type};base64,{base64_data}.
  3. Local file path: you can pass in the absolute path or relative path of the file. See the following table to pass in the correct file path.

System

File path to pass in

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, make sure that the DashScope Python SDK is installed. We recommend that you upgrade to the latest version: pip install -U dashscope. For more information, see Install SDK.

Synchronous Call

This example shows the synchronous call method 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

"""
Requirements:
    dashscope Python SDK >= 2.0.1
Install/upgrade the SDK:
    pip install -U dashscope
"""

# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
    # If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys differ by region. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# --- Helper function: 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("不支持或无法识别的图像格式")
    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}"

"""
Image input methods:
The following three methods are provided; choose one of them:

1. Public URL - for images that are already publicly accessible
2. Local file - for local development and testing
3. Base64 encoding - 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 (both absolute and relative paths are supported)
# Format: 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"                 # Use the actual path
# base_image_url = "file://" + "./base_image.jpeg"                # Use the actual path

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

def sample_sync_call_imageedit():
    print('please wait...')
    try:
        # generate is a one-step call ("submit + wait") that returns a completed Job object.
        job = client.images.generate(
            model="wanx2.1-imageedit",
            function="description_edit_with_mask",
            prompt="陶瓷兔子拿着陶瓷小花",
            # mask_image_url/base_image_url are edit-specific input fields, passed through extra_input to the request input section.
            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 status code: {e.status_code}")
        print(f"Error code: {e.code}")
        print(f"Error message: {e.message}")
        print("See the documentation: https://www.alibabacloud.com/help/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.

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

This example only shows the asynchronous call method.

Request example
import os
import dashscope
from dashscope import DashScopeError

"""
Requirements:
    dashscope Python SDK >= 2.0.1
Install/upgrade the SDK:
    pip install -U dashscope
"""

# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
    # If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys differ by region. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# 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():
    try:
        # Asynchronous call (step-by-step submission); returns a Job object that contains task_id.
        job = client.images.jobs.create(
            model="wanx2.1-imageedit",
            function="description_edit_with_mask",
            prompt="陶瓷兔子拿着陶瓷小花",
            # mask_image_url/base_image_url are edit-specific input fields, passed through extra_input to the request input section.
            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)

        # Fetch the asynchronous task information
        snapshot = client.images.jobs.fetch(job.task_id)
        print(snapshot.status)  # check the task status

        # Wait for the asynchronous task to finish (polling with exponential backoff, 24-hour total budget by default; a FAILED task raises 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 status code: {e.status_code}")
        print(f"Error code: {e.code}")
        print(f"Error message: {e.message}")
        print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    sample_async_call_imageedit()
Response example
  1. Response example of 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
}
  1. Response example of querying the 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 calls

When you use the Java SDK to process image files, you can input images in the following three ways. Choose one based on your scenario.

  1. Public URL: a publicly accessible image URL (HTTP/HTTPS).
  2. Base64 encoding: a string obtained after Base64-encoding the file, in the format data:{MIME_type};base64,{base64_data}.
  3. Local file path: only the absolute path of the file is supported. Refer to the table below and pass in the correct file path.

System

File path to pass in

Examples

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, make sure that the DashScope Java SDK is installed. We recommend that you upgrade to the latest version. For more information, see Install SDK.

Synchronous Call

This example shows the synchronous call method 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;

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

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

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

    /**
     * Image input methods: Choose one of the following three.
     *
     * 1. Use a public URL - suitable for publicly accessible images.
     * 2. Local file: Suitable for local development and testing.
     * 3. Base64 encoding: Best for private images or when data must be securely transmitted.
     */

    //[Method 1] 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
        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));
    }

    /**
     * Encodes a file into a Base64 string.
     * @param filePath The file path.
     * @return A Base64 string in the format 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);
        }
        // Detect MIME type
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("无法检测文件类型: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("不支持或无法识别的图像格式");
        }
        // Read file content and encode
        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 only shows 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;

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

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

    // If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    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
        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();
        // If DASHSCOPE_API_KEY is set as an environment variable, apiKey can be empty.
        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 of creating a task
{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}
  1. Response example of querying the 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 troubleshooting.

This API also has specific status codes, as shown below.

HTTP status code

API error code (code)

API error message (message)

Description

400

InvalidParameter

InvalidParameter

Invalid request parameters.

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 may pose infringement risks.

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

Service exception. Retry first to rule out transient issues.

Input image notes

Value passing methods

Input images support multiple string formats. The support for different calling methods is shown in the following table.

Call 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. HTTP or HTTPS protocols are supported.
  • Example value: https://xxxx/img.png.
Method 2: Use Base64 encoding

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

  • 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 mappings:

    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 preceding Base64 string is truncated for demonstration purposes. In actual use, make sure to pass the complete encoded string.

Method 3: Local file path
  • HTTP calls do not support local file paths. Only the Python SDK and Java SDK support them.
  • For the rules on passing local file paths, see Python SDK calls and Java SDK calls.

FAQ

For common questions about image models, see the FAQ documentation, which covers the following: model billing and rate limit rules, solutions to frequently reported API errors, and more.