Appearance
Wan2.5 - general image editing
Edits images using text prompts. Wan2.5 preserves subject consistency and supports multi-image fusion (up to 3 reference images). Quick start : Image editing - Wan2.7/2.6/2.5
Model overview
| Feature | Input example | Output image |
|---|---|---|
| Single-image editing | * | Change the floral dress to a vintage-style lace long dress with exquisite embroidery details on the collar and cuffs. |
| Multi-image fusion | Place the alarm clock from Image 1 next to the vase on the dining table in Image 2. |
| Model | Description | Output image specifications |
|---|---|---|
| wan2.5-i2i-preview | Wan 2.5 preview Supports single-image editing and multi-image fusion. | Image format: PNG. Image resolution: - Specify the resolution of the output image using the parameters.size parameter, in the format width*height (in pixels). - If you do not specify a resolution, the system outputs an image with 1280*1280 total pixels by default. The system preserves an aspect ratio similar to the input image: Single-image input: The aspect ratio matches the input image. - Multi-image input: The aspect ratio matches the last input image. |
Note
Check the model list and pricing for your region before calling.
Prerequisites
Before making a call, get an API key and export the API key as an environment variable. To make calls using the SDK, install the DashScope SDK. Important
The Beijing and Singapore regions have separate API keys and request endpoints. They cannot be used interchangeably. Cross-region calls lead to authentication failures or service errors.
HTTP
Image editing takes time. Use asynchronous calls: submit a task to get a task ID, then poll until ready.
Tip: Poll every 5 seconds until the task status changes to SUCCEEDED or FAILED.
Step 1: Submit a task and retrieve the task ID
Singapore : POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis
Beijing : POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesisNote
After the task is created, use the returned
task_idto query the result. Thetask_idis valid for 24 hours. Do not create duplicate tasks. Instead, use polling to retrieve the result.For guidance for beginners, see Postman.
Request parameters
## Single-image editing
curl
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \\
-H 'X-DashScope-Async: enable' \\
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \\
-H 'Content-Type: application/json' \\
-d '{
"model": "wan2.5-i2i-preview",
"input": {
"prompt": "Change the floral dress to a vintage-style lace long dress with exquisite embroidery details on the collar and cuffs.",
"images": \[
"https://img.alicdn.com/imgextra/i2/O1CN01vHOj4h28jOxUJPwY8_!!6000000007968-49-tps-1344-896.webp"
\]
},
"parameters": {
"prompt_extend": true,
"n": 1
}
}'## Multi-image fusion
curl
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \\
-H 'X-DashScope-Async: enable' \\
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \\
-H 'Content-Type: application/json' \\
-d '{
"model": "wan2.5-i2i-preview",
"input": {
"prompt": "Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
"images": \[
"https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp",
"https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
\]
},
"parameters": {
"n": 1
}
}'Headers
Content-Type <i>string* (Required) The content type of the request. Must be application/json.
Authorization *string* (Required) Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
X-DashScope-Async *string* (Required) Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be enable.
**
**Important ** If this request header is missing, the error "current user api does not support synchronous calls" is returned.
Request body
model *string* (Required) The model name. For more information, see model list and pricing. Example: wan2.5-i2i-preview.
input *object* (Required) This specifies the basic input information, such as prompts. Properties
prompt *string* (Required) Text description of the elements and visual characteristics you want in the generated image. Supports Chinese and English. Max 2,000 characters; longer content is truncated. For prompt writing guidelines, see Text-to-image prompt guide. Example: A sitting orange cat, cheerful, lively, cute, realistic, and accurate.
images *array of string* (Required) An array of URLs for input images.
Maximum: 3 images per request.
For multiple images, array order defines the sequence (Image 1, Image 2, etc.). Image limits:
Supported formats: JPEG, JPG, PNG, BMP, WEBP (PNG alpha channels ignored).
Resolution: Width and height must each be between 384 and 5,000 pixels.
The maximum file size is 10 MB. Supported input formats:
Public URL <li> Both HTTP and HTTPS are supported.
Example:
http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg. </li>Base64-encoded string <li> Format: data:{MIME_type};base64,
Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (truncated for display; use the complete string in production)
For Base64 encoding specifications, see Image input methods. </li>
negative_prompt *string* (Optional) Describes elements to exclude from the generated image. Accepts Chinese and English. Maximum: 500 characters; longer content is truncated. Example: low resolution, error, worst quality, low quality, disfigured, extra fingers, bad proportions.
parameters *object* (Optional) Controls output resolution, prompt rewriting, watermarks, and processing options. Properties
size *string* (Optional) Sets the output resolution in width*height format (default: 1280*1280).
- Total pixels must fall between 589,824 (768768) and 1,638,400 (12801280). Aspect ratio must be between 1:4 and 4:1.
- Example: 1280*1280.
Recommended resolutions and aspect ratios
- 1280*1280: 1:1
- 1024*1024: 1:1
- 800*1200: 2:3
- 1200*800: 3:2
- 960*1280: 3:4
- 1280*960: 4:3
- 720*1280: 9:16
- 1280*720: 16:9
- 1344*576: 21:9
If unspecified, defaults to 1280*1280 pixels and preserves the input aspect ratio:
- Single-image input: The aspect ratio matches the input image.
- Multi-image input: The aspect ratio matches the last input image.
n *integer* (Optional)
**
**Important ** The n parameter impacts billing---higher values increase costs. Review model pricing before calling.
Specifies the number of images to generate (1-4, default: 4). Set to 1 for cost-effective testing.
watermark *boolean* (Optional) Whether to add an "AI-generated" watermark to the bottom-right corner.
- false (default)
- true
prompt_extend *boolean* (Optional) Enables smart prompt rewriting (uses LLM enhancement for better results but requires longer processing time).
- true (default)
- false Example: true.
seed *integer* (Optional) Specifies the random seed. Range: \[0, 2147483647\]. If unspecified, the algorithm auto-generates a random seed. If specified, the algorithm generates seed, seed+1, seed+2... for each of n images. To reproduce specific results, use a fixed seed value. Note: Due to inherent randomness, identical seeds may not produce exactly identical results.
Response parameters
Successful response
Save the task_id to query the task status and result.
json
{
"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 messages.
json
{
"code": "InvalidApiKey",
"message": "No API-key provided.",
"request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
} **output** `*object*` The output information of the task.
Properties
task_id *string* The task ID. Valid for queries for 24 hours.
task_status *string* The status of the task. Enumeration values
- PENDING
- RUNNING
- SUCCEEDED
- FAILED
- CANCELED
- UNKNOWN: The task does not exist or its status is unknown.
request_id *string* Unique request identifier for tracing and troubleshooting.
code *string* Error code. Returned only for failed requests. See Error messages.
message *string* Detailed error message. Returned only for failed requests. See Error messages.
Step 2: Poll for results using the task ID
Singapore
GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
Beijing
GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}Note
Polling recommendation: Image generation is time-consuming. Use a polling mechanism with a reasonable interval, such as 10 seconds.
Task state transition: PENDING → RUNNING → SUCCEEDED or FAILED.
Result link : After a task succeeds, an image URL valid for 24 hours is returned. Download and save the image to permanent storage, such as OSS.
Request parameters
## Query task result
Replace 86ecf553-d340-4e21-xxxxxxxxx with your actual task_id. ** API keys are different for each region. For more information, see Create an API key. If you use a model in the Beijing region, replace base_url with https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx.
curl
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \\
--header "Authorization: Bearer $DASHSCOPE_API_KEY"<b>Headers**
Authorization *string* (Required) Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
URL path parameters
task_id *string* (Required) The ID of the task.
Response parameters
## Successful task execution
Image URLs are valid for only 24 hours and then automatically purged. Save generated images promptly.
json
{
"request_id": "d1f2a1be-9c58-48af-b43f-xxxxxx",
"output": {
"task_id": "7f4836cd-1c47-41b3-b3a4-xxxxxx",
"task_status": "SUCCEEDED",
"submit_time": "2025-09-23 22:14:10.800",
"scheduled_time": "2025-09-23 22:14:10.825",
"end_time": "2025-09-23 22:15:23.456",
"results": \[
{
"orig_prompt": "Change the floral dress to a vintage-style lace long dress with exquisite embroidery details on the collar and cuffs.",
"actual_prompt": "Replace the pink pleated dress with a vintage-style lace long dress with exquisite embroidery details on the collar and cuffs. Keep the person's hairstyle, makeup, and posture unchanged. The overall style should be consistent with the soft tones and classic atmosphere of the original image.",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
\],
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}## Failed task execution
When a task fails, task_status is FAILED with an error code and message. See Error messages.
json
{
"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 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 messages.
json
{
"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 occurred during execution, please try again later or contact service support."
}
\],
"task_metrics": {
"TOTAL": 2,
"SUCCEEDED": 1,
"FAILED": 1
}
},
"usage": {
"image_count": 1
}
}## Expired task query
The task_id is valid for 24 hours. After this period, queries return the following error.
json
{
"request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
"output": {
"task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
"task_status": "UNKNOWN"
}
} **output** `*object*` The output information of the task.
Properties
task_id *string* The task ID. Valid for queries for 24 hours.
task_status *string* The status of the task. Enumeration values
- PENDING
- RUNNING
- SUCCEEDED
- FAILED
- CANCELED
- UNKNOWN: The task does not exist or its status is unknown.
submit_time *string* The time when the task was submitted. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.
scheduled_time *string* The time when the task was executed. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.
end_time *string* The time when the task was completed. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.
results *array of object* An array of generation results. Each entry contains the image URL, prompt, or error details for failed generations. Properties
orig_prompt *string* The original input prompt, corresponding to the request parameter prompt.
actual_prompt *string* The optimized prompt used when prompt rewriting is enabled. Not returned when disabled.
url *string* The URL of the generated image.
code *string* The error code for a failed image generation. Returned only for partial failures.
message *string* The error message for a failed image generation. Returned only for partial failures.
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.
code *string* Error code. Returned only for failed requests. See Error messages.
message *string* Detailed error message. Returned only for failed requests. See Error messages.
usage *object* Output statistics are generated. Only successful results are counted. Properties
image_count *integer* Number of images successfully generated. Billing: Cost = Number of images × Unit price.
request_id *string* Unique request identifier for tracing and troubleshooting.
DashScope SDK
SDK parameters mirror the HTTP API, with structures adapted to each language's conventions.
The SDK handles polling internally, offering both synchronous and asynchronous call modes.
Processing time depends on queue depth and service load. The SDK waits for results automatically.
Python SDK
Important
Make sure that your DashScope Python SDK version is 1.25.2 or later.
Earlier versions may cause 'url error, please check url!' errors. See Install or upgrade the SDK.
Synchronous
Request example
This example demonstrates three ways to provide input images: public URL, Base64 encoding, or local file path.
HELPCODEESCAPE-python
import base64
import mimetypes
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Image input: Use Base64 encoding ---
# The Base64 encoding format is data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("Unsupported or unrecognized image format")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
"""
Choose one image input method:
1. Public URL - for publicly accessible images
2. Local file - for local development/testing
3. Base64 - for private images or encrypted transmission
"""
# [Method 1] Use a public image URL
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
# [Method 2] Use a local file (supports absolute and relative paths)
# Format requirement: file:// + file path
# Example (absolute path):
# image_url_1 = "file://" + "/path/to/your/image_1.png" # Linux/macOS
# image_url_2 = "file://" + "C:/path/to/your/image_2.png" # Windows
# Example (relative path):
# image_url_1 = "file://" + "./image_1.png" # Use your actual path
# image_url_2 = "file://" + "./image_2.png" # Use your actual path
# [Method 3] Use a Base64-encoded image
# image_url_1 = encode_file("./image_1.png") # Use your actual path
# image_url_2 = encode_file("./image_2.png") # Use your actual path
print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="wan2.5-i2i-preview",
prompt="Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
images=[image_url_1, image_url_2],
negative_prompt="",
n=1,
# size="1280*1280",
prompt_extend=True,
watermark=False,
seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# Save the image in the current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))Response example
URLs expire after 24 hours. Download promptly.
HELPCODEESCAPE-json
{
"status_code": 200,
"request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"orig_prompt": "Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
"actual_prompt": "Place the blue alarm clock from Image 1 to the right of the vase on the dining table in Image 2, near the edge of the tablecloth. Keep the alarm clock facing the camera, parallel to the table, with its shadow naturally cast on the table."
}
],
"submit_time": "2025-10-23 16:18:16.009",
"scheduled_time": "2025-10-23 16:18:16.040",
"end_time": "2025-10-23 16:19:09.591",
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}Asynchronous
This example uses a public URL to pass the image.
Request example
HELPCODEESCAPE-python
import os
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Use a public image URL
image_url_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"
image_url_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
def async_call():
print('----create task----')
task_info = create_async_task()
print('----wait task----')
wait_async_task(task_info)
# Create an asynchronous task
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="wan2.5-i2i-preview",
prompt="Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
images=[image_url_1, image_url_2],
negative_prompt="",
n=1,
# size="1280*1280",
prompt_extend=True,
watermark=False,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# Wait for the asynchronous task to complete
def wait_async_task(task):
rsp = ImageSynthesis.wait(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# Save file to current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# Get asynchronous task information
def fetch_task_status(task):
status = ImageSynthesis.fetch(task=task, api_key=api_key)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# Cancel the asynchronous task. Only tasks in the PENDING state can be canceled.
def cancel_task(task):
rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()Response example
- Response example for a task creation request
HELPCODEESCAPE-json
{
"status_code": 200,
"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
"code": "",
"message": "",
"output": {
"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
"task_status": "PENDING",
"results": []
},
"usage": null
}- Response example for a task query request
URLs expire after 24 hours. Download promptly.
{
"status_code": 200,
"request_id": "8ad45834-4321-44ed-adf5-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "3aff9ebd-35fc-4339-98a3-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"orig_prompt": "Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
"actual_prompt": "Place the blue alarm clock from Image 1 to the right of the vase on the dining table in Image 2, near the edge of the tablecloth. Keep the alarm clock facing the camera, parallel to the table, with its shadow naturally cast on the table."
}
],
"submit_time": "2025-10-23 16:18:16.009",
"scheduled_time": "2025-10-23 16:18:16.040",
"end_time": "2025-10-23 16:19:09.591",
"task_metrics": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"image_count": 1
}
}Java SDK
Important
Make sure that your DashScope Java SDK version is 2.22.2 or later.
Earlier versions may cause 'url error, please check url!' errors. See Install or upgrade the SDK.
Synchronous
Request example
This example demonstrates three ways to provide input images: public URL, Base64 encoding, or local file path.
HELPCODEESCAPE-java
// 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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Image2Image {
static {
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
/**
* Choose one image input method:
* 1. Public URL - for publicly accessible images
* 2. Local file - for local development/testing
* 3. Base64 - for private images or encrypted transmission
*/
//[Method 1] Public URL
static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";
//[Method 2] Local file path (file://+absolute path or file:///+absolute path)
// static String imageUrl_1 = "file://" + "/your/path/to/image_1.png"; // Linux/macOS
// static String imageUrl_2 = "file:///" + "C:/your/path/to/image_2.png"; // Windows
//[Method 3] Base64 encoding
// static String imageUrl_1 = encodeFile("/your/path/to/image_1.png");
// static String imageUrl_2 = encodeFile("/your/path/to/image_2.png");
// Set the list of images to be edited
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void syncCall() {
// Set the parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", "12345");
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-i2i-preview")
.prompt("Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.")
.images(imageUrls)
.n(1)
//.size("1280*1280")
.negativePrompt("")
.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("File does not exist: " + filePath);
}
// Detect the MIME type
String mimeType = null;
try {
mimeType = Files.probeContentType(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot detect file type: " + filePath);
}
if (mimeType == null || !mimeType.startsWith("image/")) {
throw new IllegalArgumentException("Unsupported or unrecognized image format");
}
// Read the file content and encode it
byte[] fileBytes = null;
try{
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file content: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void main(String[] args) {
syncCall();
}
}Response example
URLs expire after 24 hours. Download promptly.
HELPCODEESCAPE-json
{
"request_id": "d362685b-757f-4eac-bab5-xxxxxx",
"output": {
"task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
"actual_prompt": "Place the blue alarm clock from Image 1 to the right of the vase on the dining table in Image 2, near the edge of the tablecloth. Keep the front of the alarm clock facing the camera, parallel to the vase.",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}Asynchronous
This example uses a public URL to pass the image.
Request example
HELPCODEESCAPE-java
// 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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Image2Image {
static {
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// The API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
//Public URL
static String imageUrl_1 = "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp";
static String imageUrl_2 = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp";
// Set the list of images to be edited
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void asyncCall() {
// Set the parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", "12345");
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-i2i-preview")
.prompt("Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.")
.images(imageUrls)
.n(1)
//.size("1280*1280")
.negativePrompt("")
.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 you have set DASHSCOPE_API_KEY as an environment variable, you can leave apiKey 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
- Response example for a task creation request
HELPCODEESCAPE-json
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}- Response example for a task query request
URLs expire after 24 hours. Download promptly.
{
"request_id": "d362685b-757f-4eac-bab5-xxxxxx",
"output": {
"task_id": "bfa7fc39-3d87-4fa7-b1e6-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Place the alarm clock from Image 1 next to the vase on the dining table in Image 2.",
"actual_prompt": "Place the blue alarm clock from Image 1 to the right of the vase on the dining table in Image 2, near the edge of the tablecloth. Keep the front of the alarm clock facing the camera, parallel to the vase.",
"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}Limitations
Data retention: Task IDs and image URLs expire after 24 hours.
Content moderation : All inputs (prompts, images) and outputs are automatically moderated. Non-compliant content triggers `IPInfringementSuspect` or `DataInspectionFailed` errors. See Error messages.
Error codes
If the model call fails and returns an error message, see Error messages for resolution.
FAQ
Q: I'm migrating from Wan2.1. What API changes should I know about?
A: Parameter designs differ between versions---adjustments are required.
Wan2.1 -- general image editing: Requires both the
promptandfunctionparameters.Wan2.5 -- general image editing: Requires only
prompt---describe all operations in text.functionis deprecated.
Q: How do I view the number of model calls?
A: Usage metrics (call count, success rate) appear on the Monitoring (Singapore) or Monitoring (Beijing) page within one hour. For instructions, see How to view model call records?.