All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan - general image editing 2.5

Last Updated:Nov 14, 2025

The Wan general image editing wan2.5 model lets you edit images, fuse multiple images, and generate groups of images. You can use text, a single image, or multiple images as input, and the model maintains subject consistency.

Overview

Feature

Input example

Output image

Single-image editing

damotest2023_Portrait_photography_outdoors_fashionable_beauty_409ae3c1-19e8-4515-8e50-b3c9072e1282_2-转换自-png

Change the floral dress to a vintage-style lace long dress with exquisite embroidery details on the collar and cuffs.

a26b226d-f044-4e95-a41c-d1c0d301c30b-转换自-png

Multi-image fusion

图像编辑2图像编辑2

Place the alarm clock from image 1 next to the vase on the dining table in image 2.

图像编辑2

Model

Description

Output image specifications

wan2.5-i2i-preview

Wan 2.5 preview

Supports single-image editing and multi-image reference generation.

Image format: PNG

Image resolution:

  • Single-image editing: For a single input image, the total pixels are maintained at 1280*1280. The output image has the same aspect ratio as the input image.

  • Multi-image reference: For multiple input images, the output is a fixed 1280*1280 image by default.

Note

Before you make a call, check the Model list and pricing for your region.

Prerequisites

Before making a call, obtain an API key and set 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. Do not use them interchangeably. Cross-region calls cause authentication failures or service errors.

HTTP

Because image editing tasks can take 1 to 2 minutes to complete, the API uses asynchronous invocation. The process has two main steps: create a task, then poll for the result. The steps are as follows:

The specific running time depends on the number of tasks in the queue and the service execution status. Please be patient while the result is retrieved.

Step 1: Create a task to get a 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-synthesis

Note
  • After the task is created, use the returned task_id to query the result. The task_id is valid for 24 hours. Do not create duplicate tasks. Use polling to retrieve the result.

Request parameters

Single-image editing

 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/O1CN01FuGdH91RenU9KPeri_!!6000000002137-2-tps-1344-896.png"
        ]
    },
    "parameters": {
        "n": 1
    }
}'

Multi-image reference generation

 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/i4/O1CN01TlDlJe1LR9zso3xAC_!!6000000001295-2-tps-1104-1472.png",
            "https://img.alicdn.com/imgextra/i4/O1CN01M9azZ41YdblclkU6Z_!!6000000003082-2-tps-1696-960.png"
        ]
    },
    "parameters": {
        "n": 1
    }
}'

Request headers

Content-Type string (Required)

The content type of the request. Set this parameter to application/json.

Authorization string (Required)

The identity authentication credentials for the request. This API uses an Model Studio API key for identity authentication. Example: Bearer sk-xxxx.

X-DashScope-Async string (Required)

The asynchronous processing configuration parameter. HTTP requests support only asynchronous processing. You must set this parameter to enable.

Important

If this request header is missing, the error message "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)

Basic input information, such as prompts.

Properties

prompt string (Required)

A positive prompt that describes the desired elements and visual features in the generated image.

Supports both Chinese and English. The maximum length is 2,000 characters. Each Chinese character or letter counts as one character. Any excess characters are automatically truncated.

Example: A sitting orange cat, with a pleasant expression, lively and cute, realistic and accurate.

For tips on using prompts, see Text-to-image prompt guide.

images array of string (Required)

An array of image URLs.

  • The maximum array length is 2.

  • For multi-image input, the order of the images is determined by their order in the array.

Image limits:

  • Image format: JPEG, JPG, PNG (alpha channel not supported), BMP, WEBP.

  • Image resolution: The width and height must be between 384 and 5,000 pixels.

  • The maximum file size is 10 MB.

Supported input formats:

  1. Publicly accessible URL

    • Supports HTTP or HTTPS protocols.

    • Example: http://wanx.alicdn.com/material/20250318/stylization_all_1.jpeg.

  2. Base64-encoded image string

    • Format: data:{MIME_type};base64,{base64_data}

    • Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (This is only for illustration. The actual encoding must be complete.)

    • For complete Base64 encoding specifications, see Input image specifications.

negative_prompt string (Optional)

A negative prompt that describes content you do not want to see in the image. It can be used to restrict the image content.

Supports both Chinese and English. The maximum length is 500 characters. Any excess characters are automatically truncated.

Example: low resolution, error, worst quality, low quality, incomplete, extra fingers, bad proportions.

parameters object (Optional)

Image editing parameters. You can set the image resolution, enable intelligent prompt rewriting, add watermarks, and more.

Properties

n integer (Optional)

Important

The value of n directly affects the cost. A larger n results in a higher cost. Before making a call, confirm the model price.

The number of images to generate. The value must be between 1 and 4. The default is 4. We recommend setting this to 1 during the testing phase.

watermark boolean (Optional)

Specifies whether to add a watermark. The watermark is placed in the lower-right corner of the image, saying "AI-generated".

  • false (default)

  • true

seed integer (Optional)

A random number seed. The value must be between [0, 2147483647].

If you do not provide a seed, the algorithm automatically generates a random number to use as the seed. If you provide a seed, the algorithm generates seeds for n images based on the value of n. For example, if n=4, the algorithm generates images with seeds seed, seed+1, seed+2, and seed+3.

To improve the reproducibility of the generated results, we recommend using a fixed seed value.

Note that because model generation is probabilistic, using the same seed does not guarantee that the results will be identical every time.

Response parameters

Successful response

Save the task_id to query the task status and result.

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

Error response

The task creation failed. For more information, see Error messages to resolve the issue.

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"fb53c4ec-1c12-4fc4-a580-xxxxxx"
}

output object

The task output information.

Properties

task_id string

The task ID. The query is valid for 24 hours.

task_status string

The task status.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN

request_id string

The unique request ID. You can use this ID to trace and troubleshoot issues.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

Step 2: Query the result by task ID

Singapore region: GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}

Beijing region: GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}

Note
  • Polling suggestion: Image generation takes several minutes. Use a polling mechanism and set a reasonable query interval, such as 10 seconds, to retrieve the result.

  • Task status transition: PENDING (In queue) → RUNNING (Processing) → SUCCEEDED (Successful) or FAILED (Failed).

  • Result link: After the task is successful, an image link is returned. The link is valid for 24 hours. After you retrieve the link, immediately download and save the image to a permanent storage service, such as Alibaba Cloud OSS.

Request parameters

Query task result

Replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task ID.

The API keys for the Singapore and Beijing regions are different. Obtain an API key.
The following code provides the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Request headers

Authorization string (Required)

The identity authentication credentials for the request. This API uses an Model Studio API key for identity authentication. Example: Bearer sk-xxxx.

URL path parameters

task_id string (Required)

The task ID.

Response parameters

Task executed successfully

Image URLs are retained for only 24 hours and are automatically purged after this period. You must save the generated images promptly.

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

Task execution failed

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

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-xxxxxx",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "xxxxxx",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

Task partially failed

The model can generate multiple images in a single task. If at least one image is generated successfully, the task status is marked as SUCCEEDED, and the corresponding image URL is returned. For images that fail to generate, the result contains the reason for the failure. In addition, only successful results are counted in usage statistics. For more information, see Error messages to resolve the issue.

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

Task query expired

The task_id is valid for 24 hours. After this period, the query fails and the following error message is returned.

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

output object

The task output information.

Properties

task_id string

The task ID. The query is valid for 24 hours.

task_status string

The task status.

Enumeration

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN

submit_time string

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

scheduled_time string

The time when the task started running. The format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

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

results array of object

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

Properties

orig_prompt string

The original input prompt.

url string

The URL of the image generated by the model.

code string

The image error code. This field is returned when a task partially fails.

message string

The image error message. This field is returned when a task partially fails.

task_metrics object

The task result statistics.

Properties

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of successful tasks.

FAILED integer

The number of failed tasks.

code string

The error code for a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

message string

The detailed information about a failed request. This parameter is not returned if the request is successful. For more information, see Error messages.

usage object

Output information statistics. Only successful results are counted.

Properties

image_count integer

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

request_id string

The unique request ID. You can use this ID to trace and troubleshoot issues.

DashScope SDK

The parameter names in the SDK are mostly consistent with the HTTP. The parameter structure is encapsulated based on the language features.

Because image editing tasks take about 30 to 60 seconds, the SDK encapsulates the HTTP asynchronous invocation process at the underlying layer. It supports both synchronous and asynchronous invocation methods.

The specific running time depends on the number of tasks in the queue and the service execution status. Please be patient while the result is retrieved.

Python SDK

Note

We recommend installing the latest version of the DashScope Python SDK. Otherwise, a runtime error may occur. For more information, see Install or upgrade the SDK.

Synchronous

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

# The following is the URL for the Singapore region. If you use a model in the 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 the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and Beijing regions are different. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Input image: 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}"

"""
Image input methods:
The following three image input methods are provided. Choose one.

1. Use a public URL - Suitable for images that are already publicly accessible.
2. Use a local file - Suitable for local development and testing.
3. Use Base64 encoding - Suitable for private images or scenarios that require encrypted transmission.
"""

# [Method 1] Use a public image URL
image_url_1 = "https://img.alicdn.com/imgextra/i4/O1CN01TlDlJe1LR9zso3xAC_!!6000000001295-2-tps-1104-1472.png"
image_url_2 = "https://img.alicdn.com/imgextra/i4/O1CN01M9azZ41YdblclkU6Z_!!6000000003082-2-tps-1696-960.png"

# [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"                 # Based on the actual path
# image_url_2 = "file://" + "./image_2.png"                # Based on the actual path

# [Method 3] Use a Base64-encoded image
# image_url_1 = encode_file("./image_1.png")               # Based on the actual path
# image_url_2 = encode_file("./image_2.png")              # Based on the 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,
                          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
The URL is valid for 24 hours. Download the image 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."
            }
        ],
        "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

Request example
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 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 the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and Beijing regions are different. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")


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=["https://img.alicdn.com/imgextra/i4/O1CN01TlDlJe1LR9zso3xAC_!!6000000001295-2-tps-1104-1472.png",
                                            "https://img.alicdn.com/imgextra/i4/O1CN01M9azZ41YdblclkU6Z_!!6000000003082-2-tps-1696-960.png"],
                                    negative_prompt="",
                                    n=1,
                                    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 finish
def wait_async_task(task):
    rsp = ImageSynthesis.wait(task)
    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)
    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 an asynchronous task. Only tasks in the PENDING state can be canceled.
def cancel_task(task):
    rsp = ImageSynthesis.cancel(task)
    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

1. Response example for creating a task

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

2. Response example for querying a task result

The URL is valid for 24 hours. Download the image 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."
            }
        ],
        "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

Note

We recommend installing the latest version of the DashScope Java SDK. Otherwise, a runtime error may occur. For more information, see Install or upgrade the SDK.

Synchronous

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

mport 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 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 the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // The API keys for the Singapore and Beijing regions are different. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * Image input methods: Choose one of the three.
     *
     * 1. Use a public URL - Suitable for images that are already publicly accessible.
     * 2. Use a local file - Suitable for local development and testing.
     * 3. Use Base64 encoding - Suitable for private images or scenarios that require encrypted transmission.
     */

    // [Method 1] Public URL
    static String imageUrl_1 = "https://img.alicdn.com/imgextra/i4/O1CN01TlDlJe1LR9zso3xAC_!!6000000001295-2-tps-1104-1472.png";
    static String imageUrl_2 = "https://img.alicdn.com/imgextra/i4/O1CN01M9azZ41YdblclkU6Z_!!6000000003082-2-tps-1696-960.png";

    // [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("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)
                        .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 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 file content and encode
        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
The URL is valid for 24 hours. Download the image 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.",
                "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

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.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 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 the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
    // The API keys for the Singapore and Beijing regions are different. To get an API key, see 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/i4/O1CN01TlDlJe1LR9zso3xAC_!!6000000001295-2-tps-1104-1472.png";
    static String imageUrl_2 = "https://img.alicdn.com/imgextra/i4/O1CN01M9azZ41YdblclkU6Z_!!6000000003082-2-tps-1696-960.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 asyncCall() {
        // Set the parameters
        Map<String, Object> parameters = new HashMap<>();
        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)
                        .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();
        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 null.
        ImageSynthesisResult result = is.fetch(taskId, null);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }


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

1. Response example for creating a task

{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}

2. Response example for querying a task result

The URL is valid for 24 hours. Download the image 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.",
                "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
    }
}

Limits

  • Data validity: The task_id and image URL are both valid for only 24 hours. After this period, they cannot be queried or downloaded.

  • Content moderation: Input prompts, input images, and output images all undergo content moderation. Requests containing prohibited content will result in an "IPInfringementSuspect" or "DataInspectionFailed" error. For more information, see Error messages.

  • Network access configuration: Image links are stored in Alibaba Cloud OSS. If your business system cannot access external OSS links due to security policies, add the following OSS domain names to your network access whitelist.

    # OSS domain name list
    dashscope-result-bj.oss-cn-beijing.aliyuncs.com
    dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com
    dashscope-result-sh.oss-cn-shanghai.aliyuncs.com
    dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com
    dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com
    dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com
    dashscope-result-hy.oss-cn-heyuan.aliyuncs.com
    dashscope-result-cd.oss-cn-chengdu.aliyuncs.com
    dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com
    dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com

Input image specifications

The input image images parameter is an array. Each element supports the following three input methods:

Method 1: Public URL

  • A publicly accessible address that supports HTTP/HTTPS.

  • Example: https://example.com/images/cat.png.

Method 2: Base64 encoding

Example code

import base64
import mimetypes


# --- For 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}"


if __name__ == "__main__":
    print(encode_file("./image_demo_input.png"))
  • Example: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDg...... (This is only a snippet due to length limitations). When making a call, pass the complete string.

  • Encoding format: Follows the data:{MIME_type};base64,{base64_data} format, where:

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

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

      Image format

      MIME Type

      JPEG

      image/jpeg

      JPG

      image/jpeg

      PNG

      image/png

      BMP

      image/bmp

      WEBP

      image/webp

Method 3: Local file path (SDK only)

  • Python SDK: Supports passing both absolute and relative paths of files. The file path rules are as follows:

    System

    Passed file path

    Example (absolute path)

    Example (relative path)

    Linux or macOS system

    file://{absolute or relative path of the file}

    file:///home/images/test.png

    file://./images/test.png

    Windows system

    file://D:/images/test.png

    file://./images/test.png

  • Java SDK: Supports passing only the absolute path of files. The file path rules are as follows:

    System

    Passed file path

    Example (absolute path)

    Linux or macOS system

    file://{absolute path of the file}

    file:///home/images/test.png

    Windows system

    file:///{absolute path of the file}

    file:///D:/images/test.png

Billing and throttling

  • For the model's free quota and billing unit price, see Models.

  • For model rate limits, see Wan.

  • Billing description:

    • Billing is based on the number of successfully generated images. You are charged only when the query result API returns a task_status of SUCCEEDED and an image is successfully generated.

    • No fees are incurred if the model call fails or a processing error occurs. This also does not consume your free quota.

Error codes

If a call fails, see Error messages for troubleshooting.

FAQ

Q: How can I view the model call volume?

A: One hour after the model call is complete, you can go to the Model Observation (Singapore)Model Observation (Beijing) page to view metrics such as the number of model calls and the success rate. For more information, see How do I view model call records?