Remove unwanted elements from an image (people, pets, objects, text, watermarks) and fill the erased area with the matching background. Control the erase region with a mask image.
This API runs asynchronously: submit a task, then poll for the result with the returned task ID.
Related guide: Image erase completion
-
This model is available only in the China (Beijing) region. To explore available models, go to the Models page.
-
image-erase-completion is currently free trial only. Once the quota is exhausted, the model can no longer be called (paid usage not supported). For alternatives, see Image editing - Qwen or Image editing - Wan.
Prerequisites
Before you begin, make sure that you have:
-
A Model Studio API key
-
The API key configured as an environment variable
How it works
Image processing takes time, so the API uses a two-step async pattern:
-
Create a task -- POST a request with input images and parameters. The response contains a
task_id. -
Query the result -- GET the task status using the
task_id. Whentask_statusisSUCCEEDED, the response includesoutput_image_url.
Task results and output image URL are valid for 24 hours. Download the image before expiration.
Step 1: Create a task
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis
Request headers
| Header | Type | Required | Description |
|---|---|---|---|
| Content-Type | string | Yes | Set to application/json. |
| Authorization | string | Yes | Use Bearer token format: Bearer d1***2a |
| X-DashScope-Async | string | Yes | Set to enable for the async workflow. |
Request body
| Parameter | Type | Required | Description |
|---|---|---|---|
| model | string | Yes | The model name. Set to image-erase-completion. |
| input | object | Yes | Input images. See Input parameters. |
| parameters | object | No | Processing options. See Processing parameters. |
Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL or Base64-encoded data of the source image. See Image requirements. |
| mask_url | string | Yes | URL or Base64-encoded mask defining the erase area. Non-zero pixels mark the region to erase. See Mask requirements and Create a mask. |
| foreground_url | string | No | URL or Base64-encoded mask defining the area to retain. Non-zero pixels mark the region to preserve. See Mask requirements and Retain specific elements. |
Processing parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| fast_mode | bool | false | Reduces inference time to ~1/4 of standard mode. Use when high detail is not required. |
| dilate_flag | bool | true | Controls the mask edge dilation. Set to true for algorithm-generated masks (auto edge expansion) or false for manually drawn masks. |
| add_watermark | bool | true | Add a Generated by AI watermark to the lower-left corner of the output image. |
Response
| Field | Type | Description |
|---|---|---|
| output.task_id | string | Unique task ID. Use this to query the result in Step 2. |
| output.task_status | string | Task status: PENDING, RUNNING, SUSPENDED, SUCCEEDED, or FAILED. |
| request_id | string | Unique request ID for troubleshooting. |
| code | string | Error code. Returned only on failure. |
| message | string | Error message. Returned only on failure. |
Successful response
{
"output": {
"task_status": "PENDING",
"task_id": "53950fb7-281a-4e60-b543-xxxxxxxxxxxx"
},
"request_id": "1027557e-8c3f-9db5-8cd2-xxxxxxxxxxxx"
}
Error response
{
"code": "InvalidApiKey",
"message": "Invalid API-key provided.",
"request_id": "fb53c4ec-1c12-4fc4-a580-xxxxxxxxxxxx"
}
Step 2: Query the result
GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
Request headers
| Header | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Yes | Use Bearer token format: Bearer d1***2a |
Path parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| task_id | string | Yes | The task ID returned in Step 1. |
Response
| Field | Type | Description |
|---|---|---|
| output.task_id | string | Task ID. |
| output.task_status | string | Task status: PENDING, RUNNING, SUSPENDED, SUCCEEDED, or FAILED. |
| output.task_metrics | object | Task progress metrics. Contains TOTAL, SUCCEEDED, and FAILED subtask counts. |
| output.submit_time | string | Time the task was submitted. |
| output.scheduled_time | string | Time the task started running. |
| output.end_time | string | Time the task completed. |
| output.output_image_url | string | URL of the output image. Valid for 24 hours. |
| output.code | string | Error code. Returned only if the task fails. |
| output.message | string | Error message. Returned only if the task fails. |
| usage.image_count | integer | Number of generated images. |
| request_id | string | Unique request ID for troubleshooting. |
Completed task
{
"request_id": "b67df059-ca6a-9d51-afcd-9b3c4456b1e2",
"output": {
"task_id": "53950fb7-281a-4e60-b543-xxxxxxxxxxxx",
"task_status": "SUCCEEDED",
"submit_time": "2024-05-16 13:50:01.247",
"scheduled_time": "2024-05-16 13:50:01.354",
"end_time": "2024-05-16 13:50:27.795",
"output_image_url": "http://xxx/result.png"
},
"usage": {
"image_count": 1
}
}
In-progress task
{
"request_id": "7574ee8f-38a3-4b1e-9280-11c33ab46e51",
"output": {
"task_id": "53950fb7-281a-4e60-b543-xxxxxxxxxxxx",
"task_status": "RUNNING",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
}
}
Failed task
{
"request_id": "4246a1de-2aab-9b49-ba87-e0d12e221a06",
"output": {
"task_id": "53950fb7-281a-4e60-b543-xxxxxxxxxxxx",
"task_status": "FAILED",
"submit_time": "2024-03-22 12:07:07.183",
"scheduled_time": "2024-03-22 12:07:07.253",
"end_time": "2024-03-22 12:07:07.604",
"code": "InternalError.Algo",
"message": "video generation error"
}
}
Image and mask requirements
Image requirements
These constraints apply to the source image (image_url):
| Constraint | Value |
|---|---|
| Formats | JPEG, JPG, PNG, BMP, WEBP |
| Resolution | 512 x 512 to 4096 x 4096 pixels |
| Side length | 512 to 4096 pixels per side |
| File size | 10 MB max |
| URL | URLs must be publicly accessible (HTTP/HTTPS) without Chinese characters. |
Mask requirements
These constraints apply to mask_url and foreground_url:
| Constraint | Value |
|---|---|
| Formats | JPG, JPEG, PNG, HEIF, WEBP |
| Resolution | 512 x 512 to 4096 x 4096 pixels |
| Side length | 512 to 4096 pixels per side |
| File size | 10 MB max |
| URL | Must be publicly accessible via HTTP or HTTPS |
Create a mask
Paint on a blank canvas matching the source image's dimensions. Painted areas (non-zero pixels) define the erase region.
Or use Human instance segmentation to generate the erase mask.
Retain specific elements
Provide a foreground_url mask to prevent specific elements from erasure. Paint the retain area on a blank canvas matching the source image's dimensions. Non-zero pixels mark the retained region.
For example, use Human instance segmentation with a person ID to generate a mask that preserves that person during erasure.
Examples
Examples use the two-step async pattern: creating a task, then querying with the returned task ID.
cURL
Create a task:
curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"model": "image-erase-completion",
"input": {
"image_url": "<your-source-image-url>",
"mask_url": "<your-mask-image-url>"
},
"parameters": {
"dilate_flag": true
}
}'
Query the result:
curl -X GET \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
https://dashscope.aliyuncs.com/api/v1/tasks/<your-task-id>
Replace the following placeholders with your values:
| Placeholder | Description | Example |
|---|---|---|
<your-source-image-url> |
Publicly accessible URL of the source image | https://example.com/person-on-beach.png |
<your-mask-image-url> |
Publicly accessible URL of the mask image | https://example.com/mask-of-person.png |
<your-task-id> |
Task ID from the create task response | 53950fb7-281a-4e60-b543-xxxxxxxxxxxx |
Python
import os
import time
import requests
# Load API key from environment variable
api_key = os.environ.get("DASHSCOPE_API_KEY")
base_url = "https://dashscope.aliyuncs.com/api/v1"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"X-DashScope-Async": "enable"
}
# Step 1: Create a task
create_response = requests.post(
f"{base_url}/services/aigc/image2image/image-synthesis",
headers=headers,
json={
"model": "image-erase-completion",
"input": {
"image_url": "<your-source-image-url>",
"mask_url": "<your-mask-image-url>"
},
"parameters": {
"dilate_flag": True
}
}
)
task_id = create_response.json()["output"]["task_id"]
print(f"Task created: {task_id}")
# Step 2: Poll for the result
query_headers = {"Authorization": f"Bearer {api_key}"}
while True:
result = requests.get(
f"{base_url}/tasks/{task_id}",
headers=query_headers
).json()
status = result["output"]["task_status"]
if status in ("SUCCEEDED", "FAILED"):
break
print(f"Status: {status}, waiting...")
time.sleep(3)
# Step 3: Download the output image
if status == "SUCCEEDED":
image_url = result["output"]["output_image_url"]
print(f"Output image: {image_url}")
# Download and save the image (URL expires in 24 hours)
image_data = requests.get(image_url).content
with open("output-image.png", "wb") as f:
f.write(image_data)
print("Image saved to output-image.png")
else:
print(f"Task failed: {result['output'].get('message', 'Unknown error')}")
Java
import java.io.*;
import java.net.URI;
import java.net.http.*;
import java.nio.file.*;
public class ImageEraseCompletion {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String baseUrl = "https://dashscope.aliyuncs.com/api/v1";
HttpClient client = HttpClient.newHttpClient();
// Step 1: Create a task
String requestBody = """
{
"model": "image-erase-completion",
"input": {
"image_url": "<your-source-image-url>",
"mask_url": "<your-mask-image-url>"
},
"parameters": {
"dilate_flag": true
}
}
""";
HttpRequest createRequest = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/services/aigc/image2image/image-synthesis"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
.header("X-DashScope-Async", "enable")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> createResponse = client.send(
createRequest, HttpResponse.BodyHandlers.ofString());
// Parse task_id from JSON response
String responseBody = createResponse.body();
String taskId = responseBody.split("\"task_id\":\"")[1].split("\"")[0];
System.out.println("Task created: " + taskId);
// Step 2: Poll for the result
String status;
String resultBody;
do {
Thread.sleep(3000);
HttpRequest queryRequest = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/tasks/" + taskId))
.header("Authorization", "Bearer " + apiKey)
.GET()
.build();
HttpResponse<String> queryResponse = client.send(
queryRequest, HttpResponse.BodyHandlers.ofString());
resultBody = queryResponse.body();
status = resultBody.split("\"task_status\":\"")[1].split("\"")[0];
System.out.println("Status: " + status);
} while (!status.equals("SUCCEEDED") && !status.equals("FAILED"));
// Step 3: Download the output image
if (status.equals("SUCCEEDED")) {
String imageUrl = resultBody.split("\"output_image_url\":\"")[1].split("\"")[0];
HttpRequest imageRequest = HttpRequest.newBuilder()
.uri(URI.create(imageUrl))
.GET()
.build();
HttpResponse<byte[]> imageResponse = client.send(
imageRequest, HttpResponse.BodyHandlers.ofByteArray());
Files.write(Path.of("output-image.png"), imageResponse.body());
System.out.println("Image saved to output-image.png");
} else {
System.out.println("Task failed: " + resultBody);
}
}
}
Node.js
const https = require('https');
const fs = require('fs');
const apiKey = process.env.DASHSCOPE_API_KEY;
const baseUrl = 'https://dashscope.aliyuncs.com/api/v1';
function request(method, url, headers, body) {
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const options = {
hostname: urlObj.hostname,
path: urlObj.pathname,
method,
headers
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => resolve({ status: res.statusCode, body: data }));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
async function main() {
// Step 1: Create a task
const createResponse = await request(
'POST',
`${baseUrl}/services/aigc/image2image/image-synthesis`,
{
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'X-DashScope-Async': 'enable'
},
JSON.stringify({
model: 'image-erase-completion',
input: {
image_url: '<your-source-image-url>',
mask_url: '<your-mask-image-url>'
},
parameters: {
dilate_flag: true
}
})
);
const taskId = JSON.parse(createResponse.body).output.task_id;
console.log(`Task created: ${taskId}`);
// Step 2: Poll for the result
let status, result;
do {
await new Promise(resolve => setTimeout(resolve, 3000));
const queryResponse = await request(
'GET',
`${baseUrl}/tasks/${taskId}`,
{ 'Authorization': `Bearer ${apiKey}` }
);
result = JSON.parse(queryResponse.body);
status = result.output.task_status;
console.log(`Status: ${status}`);
} while (status !== 'SUCCEEDED' && status !== 'FAILED');
// Step 3: Download the output image
if (status === 'SUCCEEDED') {
const imageUrl = result.output.output_image_url;
console.log(`Output image: ${imageUrl}`);
https.get(imageUrl, (res) => {
const fileStream = fs.createWriteStream('output-image.png');
res.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
console.log('Image saved to output-image.png');
});
});
} else {
console.log(`Task failed: ${result.output.message || 'Unknown error'}`);
}
}
main().catch(console.error);
Error codes
For common DashScope error codes, see Error messages.
The following error codes are specific to this API:
| HTTP status code | Error code | Error message | Description |
|---|---|---|---|
| 400 | InvalidParameter.JsonPhrase | input json error | The request body contains invalid JSON. |
| 400 | InvalidParameter.FileDownload | oss download error | Failed to download the input image from the URL. Verify the URL is publicly accessible. |
| 400 | InvalidParameter.ImageFormat | read image error | The image format is unsupported or the file is corrupted. |
| 400 | InvalidParameter.ImageContent | The image content does not comply with green network verification | The image content violates content moderation policies. |
| 400 | InvalidParameter | the parameters must conform to the specification: xxx | A parameter value is outside the valid range. Check the error message for details. |
| 400 | InvalidParameter.ImageResolution | the size of input image is too small or too large | The image resolution is outside the 512 x 512 to 4096 x 4096 pixel range. |
| 500 | InternalError.Algo | algorithm process error | An internal algorithm error occurred. Retry the request. |
| 500 | InternalError.FileUpload | oss upload error | Failed to upload the output file. Retry the request. |