General image editing - Wan2.1
Edit images with text prompts using the Wan model: outpainting, watermark removal, style transfer, instruction-based editing, inpainting, and restoration.
ImportantThis document applies only to the China (Beijing) region. Use an API key from this region.
Model overview
Performance showcase
Original image |
Change her hair to red |
Put a pair of sunglasses on her |
Convert to French picture-book style |
For more examples, see Key capabilities.
QuickStart
Prerequisites
Before you call the API, obtain and configure an API Key, and then configure the API Key in environment variables. If you call the API through the DashScope SDK, you also need to install the SDK.
Sample Code
This section demonstrates how to call the general image editing API to complete a "local repainting" task.
The SDK encapsulates the asynchronous processing logic at the underlying layer, and its high-level interface behaves as a synchronous call (that is, a single request that waits for the final result to return); the curl example, by contrast, corresponds to two separate asynchronous API interfaces: one for submitting a task and the other for querying the result.
Python
This example 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. Please 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
}
}
Java
This example 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. Please 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
}
}
curl
This example covers the entire process from creating a task, polling the status, to retrieving and saving the result.
Note
- For asynchronous calls, you must set the Header parameter
X-DashScope-Asynctoenable. - The
task_idof an asynchronous task can be queried for 24 hours; after that, the task status becomesUNKNOWN.
Step 1: Send a task creation request
This request returns a task ID (task_id).
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
}
}'
Response example{
"output": {
"task_status": "PENDING",
"task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
},
"request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}
Step 2: Query the result by task ID
Use the task_id obtained in the previous step to poll the task status through the API until task_status becomes SUCCEEDED or FAILED.
Please replace 86ecf553-d340-4e21-xxxxxxxxx with your 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 exampleThe image URL is valid for 24 hours. Please download the image 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
}
}
Key capabilities
The general image editing API uses the function parameter to specify different image editing capabilities. All capabilities follow the calling method described in QuickStart.
The following uses curl calls as examples and lists only the input and parameters JSON fragments specific to each feature, to illustrate what needs to be configured in the request body.
Note: A complete curl request should include top-level fields such as model, input, and parameters. For the specific structure, refer to General Image Edit API reference.
Global stylization
Transfers the entire image to a specified artistic style. Use cases include picture book creation and social media illustrations (generating backgrounds or concept images that match a specific visual style).
-
How to use: Set the
functionparameter tostylization_all. -
Supported styles:
- French picture book style
- Gold foil art style
-
Parameters used together:
parameters.strength(0.0-1.0, default 0.5) controls the degree of modification; the smaller the value, the closer the result to the original image. -
Prompt tips: Use the "convert to XX style" phrasing, for example, "convert to French picture book style".
Input image | Output image | |
|---|---|---|
Prompt: convert to French picture book style | Prompt: convert to gold foil art style | |
|
|
|
|
|
|
Control the degree of image modification with strength
Use the parameters.strength parameter to control the degree of image modification. This parameter is optional, with a value range of [0.0, 1.0] and a default value of 0.5. The closer the value is to 0, the closer the result to the original image; the closer the value is to 1, the greater the modification to the original image.
Input prompt: Convert to French picture book style.
Input image | Output image | ||
|---|---|---|---|
strength=0.0 (minimum) | strength=0.5 (default) | strength=1.0 (maximum) | |
|
|
|
|
Local stylization
Applies style transfer only to a local region of the image. Use cases include personalized customization (such as stylizing a person's clothing) and advertising design (highlighting products).
-
How to use: Set the
functionparameter tostylization_local. -
Supported styles: The Chinese-English correspondence is as follows:
- Ice sculpture: ice
- Cloud: cloud
- Festive lantern: chinese festive lantern
- Wooden: wooden
- Blue and white porcelain: blue and white porcelain
- Fluffy: fluffy
- Yarn: weaving
- Balloon: balloon
-
Prompt tips: Use the "turn XX into XX style" phrasing, for example, "turn the house into wooden style".
Input image | Output image | |||
|---|---|---|---|---|
|
Ice sculpture |
Cloud |
Festive lantern |
Wooden |
Blue and white porcelain |
Fluffy |
|
Balloon | |
Instruction-based editing
No region needs to be specified; image content can be added or modified through text instructions only. Use cases include simple edits that do not require precise positioning, such as adding accessories to a person or changing hair color.
- How to use: Set the parameter
functiontodescription_edit. - Parameters used together:
parameters.strength(0.0-1.0, default 0.5) controls the extent of modification; the smaller the value, the closer the result to the original image. - Prompt tips: Explicitly write action descriptions such as "add" or "modify". For deletion, inpainting is recommended.
Capability | Input image | Output image |
|---|---|---|
Add an element |
|
Add a pair of sunglasses to the kitten. |
Modify an element |
|
Change her hair to red. |
Control the extent of image modification with strength
Use the parameters.strength parameter to control the degree of image modification. This parameter is optional, with a value range of [0.0, 1.0] and a default value of 0.5. The closer the value is to 0, the closer the result to the original image; the closer the value is to 1, the greater the modification to the original image.
Input prompt: Change the clothes she is wearing into a beach shirt with a colorful print.
Input image | Output image | ||
|---|---|---|---|
strength=0.0 (minimum) | strength=0.5 (default) | strength=1.0 (maximum) | |
|
|
|
|
Inpainting
Add, modify, or delete content in a specified region by providing a mask image that marks the painted area. Use cases include edits that require precise control of the region, such as changing outfits, replacing objects, and removing distractions.
-
How to use: Set the parameter
functiontodescription_edit_with_mask. -
Mask requirements:
mask_image_urlmust be provided; in the mask image, white areas are the regions to edit, and black areas are preserved. -
Prompt tips: Explicitly write action descriptions such as "add", "modify" and describing the content after deletion.
- Add/modify: You can describe the action ("Add a hat to the puppy") or the final result ("A puppy wearing a hat").
- Delete: If the object to delete is small,
promptcan be left empty (""); if the object is large,promptmust describe the background content that should appear after deletion (for example, "A transparent glass vase on a table"), rather than "Delete the teddy bear".
| Capability | Input image | Input mask image(White indicates the region to edit) | Output image |
|---|---|---|---|
| Add an element | ![]() | ![]() | ![]() Add a hat to the puppy.
|
| Modify an element | ![]() | ![]() | ![]() A ceramic rabbit holding a ceramic flower.
|
| Delete an element | ![]() | ![]() | ![]() A transparent glass vase on a table.
|
Remove text and watermarks
Note
Legal risk noticeUsing this feature to process copyrighted images (for example, removing another party's brand watermark) may constitute infringement. Please ensure you have the legal right to use the images you process, and you bear all related legal liability yourself.
Remove Chinese or English characters or common watermarks from images. Use cases include reprocessing source materials and cleaning up advertising images.
- How to use: Set the parameter
functiontoremove_watermark. - Prompt tips: You can use a general instruction such as "Remove the text in the image", or specify a type such as "Remove the English text".
Input image | Output image (text in the image removed) |
|---|---|
|
|
|
|
Outpainting
Proportionally expands the canvas in the four directions (top, bottom, left, and right) of the image and intelligently fills in content. Use cases include: adjusting the composition, and expanding a vertical image into a horizontal one to fit different media sizes.
- How to use: Set the parameter
functiontoexpand. - Parameters used together:
top_scale,bottom_scale,left_scale,right_scaleinparameterscontrol the expansion ratio in the four directions respectively (e.g., setting all of them to 1.5 means expanding to 1.5 times the original size). - Prompt tips: Describe the complete scene content you expect to see after expansion.
Input image | Output image |
|---|---|
|
|
Image super-resolution
Enhances image clarity and supports upscaling, making low-resolution or blurry images clear. Use cases include: restoring old photos, and increasing the resolution of assets to meet high-definition printing or display requirements.
- How to use: Set the parameter
functiontosuper_resolution. - Parameters used together:
parameters.upscale_factor(1-4, default 1) controls the upscale factor. When the value is 1, only the clarity is enhanced without upscaling. - Prompt tips: You can use "image super-resolution" or describe the image content.
Input image (blurred image) | Output image (clear image) |
|---|---|
|
|
Image colorization
Converts black-and-white or grayscale images into color images (black-and-white/grayscale → color). Use cases include: colorizing historical photos, and filling in colors for line art or grayscale images.
- How to use: Set the parameter
functiontocolorization. - Prompt tips: You can leave it empty and let the model colorize automatically, or specify the colors of key elements through the prompt (e.g., "blue background, yellow leaves").
Input image | Output image |
|---|---|
|
|
Line art-to-image (doodle painting supported)
Generates a new image based on the contour (line art) of the input image combined with the prompt. Use cases include: architectural concept design, illustration design, and doodle painting.
-
How to use: Set the parameter
functiontodoodle. -
Parameters used together:
parameters.is_sketch, which controls the model's generation result.false(default): The input is an RGB image, and the model first extracts the line art and then generates the image (RGB image → line art → new image).true: The input is an RGB image (such as a doodle or line art), and the model generates the image directly based on it (RGB image → new image).
-
Prompt tips: Describe the image content you expect to generate; the more specific the description, the better the generation result.
Request example 1: line art-to-image
{
"input": {
"function": "doodle",
"prompt": "北欧极简风格的客厅。",
"base_image_url": "http://wanx.alicdn.com/material/20250318/doodle_1.png"
},
"parameters": {
"is_sketch": false
}
}
Capability | Input image | Output image |
|---|---|---|
Line art-to-image (is_sketch=false) |
|
A living room in Nordic minimalist style. |
Doodle painting (is_sketch=true) |
|
A tree in anime style. |
Image generation with cartoon character references
Note
Legal risk noticeUsing this feature to process copyrighted cartoon characters may constitute infringement. Please ensure you have the legal right to use the referenced characters, or use characters of your own creation, and bear all relevant legal responsibilities yourself.
- How to use: Set the parameter
functiontocontrol_cartoon_feature. - Prompt tips: Use the "cartoon character..." pattern to describe the character's actions and environment in detail.
Input image | Output image |
|---|---|
|
|
Going live
Best practices
- Asynchronous polling: Use graduated polling intervals (e.g., every 3s for 30s, then increase) to avoid rate limits.
- Parameter tuning: Test key parameters like
strengthin small-scale trials before production to find optimal values. - Image storage: Result URLs expire after 24 hours. Download and transfer to persistent storage (e.g., OSS) promptly.
Risk prevention
- Error handling: Check
task_statusin query results. IfFAILED, recordcodeandmessagefor troubleshooting. Transient errors (e.g., timeouts) may succeed on retry. - Content moderation: All input and output is reviewed for compliance. Non-compliant content returns
DataInspectionFailed.
API reference
Input and response parameters are documented in the General image editing API reference.
Billing and rate limiting
-
For model free quotas and unit prices, see Models and pricing.
-
For model rate limiting, see Wanxiang.
-
Billing details:
- Billed per successfully generated image. Charges apply only when
task_statusisSUCCEEDED. - Failed calls do not incur charges or consume Free quota for new users.
- General image editing also supports savings plans. Offset order: free quota > savings plan > pay-as-you-go.
- Billed per successfully generated image. Charges apply only when
Error codes
If the model call fails and returns an error message, see Error codes for resolution.
FAQ
Q: Why did my task fail (FAILED)?Common causes:
- Content moderation failure: Input or output triggered security policy.
- Parameter error: Invalid request parameters (e.g., incorrect
functionname or inaccessible URL). - Internal model error: The model encountered an unexpected issue during processing. Check the
codeanderrorfields in the task query response to get the specific error code and message for troubleshooting.





















Yarn






























