すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:画像編集 - Wan2.5 から 2.7

最終更新日:Jul 02, 2026

Wan モデルを使用して、テキスト指示で画像を編集します。マルチ画像の入出力、画像融合、被写体維持、オブジェクト検出をサポートしています。

クイックスタート

wan2.7-image-pro を使用して、2 つの入力画像とテキストプロンプトから編集済み画像を生成します。

プロンプト:画像 2 のグラフィティを画像 1 の車にスプレーペイントする

入力画像 1

入力画像 2

出力画像 (wan2.7-image-pro)

umbrella

input2

1774509357_902b1408-2026-03-30-16-12-31

呼び出しを行う前に、API キーを取得し、API キーを環境変数としてエクスポートしてください。SDK を使用して呼び出しを行うには、DashScope SDK をインストールしてください。

同期呼び出し

重要

DashScope Python SDK のバージョンが 1.25.15 以降、DashScope Java SDK のバージョンが 2.22.13 以降であることを確認してください。

Python

リクエスト例

import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# 以下はシンガポールリージョンの base_url です。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 エンコーディング関数 ---
# 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}"

"""
画像入力方法:
以下は 3 つの画像入力方法です。いずれか 1 つを選択してください。
1. パブリック URL を使用 - パブリックにアクセス可能な画像に適しています。
2. ローカルファイルを使用 - ローカルでの開発およびテストに適しています。
3. Base64 エンコーディングを使用 - プライベート画像や暗号化された伝送が必要なシナリオに適しています。
"""
# [方法 1] パブリック画像 URL を使用
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# [方法 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [方法 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

message = Message(
    role="user",
    content=[
        {"text": "Spray the graffiti from image 2 onto the car in image 1"},
        {"image": image_1},
        {"image": image_2},
    ],
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
    model="wan2.7-image-pro",
    api_key=api_key,
    messages=[message],
    watermark=False,
    n=1,
    size="2K",  # wan2.7-image-pro は、テキストからの画像生成でのみ 4K 解像度をサポートします。画像編集とマルチ画像生成は最大 2K 解像度をサポートします。
)

# 結果の画像 URL を抽出し、画像をローカルファイルに保存します。
if rsp.status_code == 200:
    for i, choice in enumerate(rsp.output.choices):
        for j, content in enumerate(choice["message"]["content"]):
            if content.get("type") == "image":
                image_url = content["image"]
                file_name = f"output_{i}_{j}.png"
                # 結果の URL は 24 時間有効です。速やかにダウンロードしてください。
                urllib.request.urlretrieve(image_url, file_name)
                print(f"Image saved to {file_name}")
else:
    print(f"Failed: status_code={rsp.status_code}, message={rsp.message}")

レスポンス例

URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
    "status_code": 200,
    "request_id": "81d868c6-6ce1-92d8-a90d-d2ee71xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "audio": null,
        "finished": true
    },
    "usage": {
        "input_tokens": 18790,
        "output_tokens": 2,
        "characters": 0,
        "image_count": 1,
        "size": "2985*1405",
        "total_tokens": 18792
    }
}

Java

リクエスト例

import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro 画像編集 - 同期呼び出しの例
 */
public class Main {

    static {
        // 以下はシンガポールリージョンの URL です。base_url はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:apiKey="sk-xxx"
    // API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 エンコーディング関数 ---
    // Base64 エンコーディング形式:data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 画像入力方法の説明:
         * 以下に 3 つの画像入力方法が提供されています。いずれか 1 つを選択してください。
         * 1. パブリック URL を使用:パブリックにアクセス可能な画像に適しています。
         * 2. ローカルファイルを使用:ローカルでの開発およびテストに適しています。
         * 3. Base64 エンコーディングを使用:プライベート画像や暗号化された伝送が必要なシナリオに適しています。
         */
        // 方法 1:パブリック画像 URL を使用します。
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // 方法 2:ローカルファイルを使用します。絶対パスと相対パスの両方がサポートされています。
        // フォーマット:file:// + ファイルパス
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // 方法 3:Base64 エンコードされた画像を使用します。
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // マルチ画像入力メッセージを構築します。
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // マルチ画像入力がサポートされています。複数の参照画像を提供できます。
                        Collections.singletonMap("text", "Spray the graffiti from image 2 onto the car in image 1"),
                        Collections.singletonMap("image", image1),
                        Collections.singletonMap("image", image2)
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .messages(Collections.singletonList(message))
                .n(1)
                .size("2K") // wan2.7-image-pro の場合、テキストからの画像生成シナリオのみが 4K 解像度をサポートします。画像編集とコラージュ生成は最大 2K 解像度をサポートします。
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---sync call for image editing, please wait a moment----");
            result = imageGeneration.call(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        // 結果の画像 URL を抽出し、ローカルファイルに保存します。
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // 結果の URL は 24 時間有効です。速やかに画像をダウンロードしてください。
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        basicCall();
    }
}

レスポンス例

URL は 24 時間有効です。速やかに保存してください。
{
    "requestId": "1bf6173a-e8de-9f75-94d3-5e618f875xxx",
    "usage": {
        "input_tokens": 18790,
        "output_tokens": 2,
        "total_tokens": 18792,
        "image_count": 1,
        "size": "2985*1405"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

curl

リクエスト例
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
                        {"text": "Spray-paint the graffiti from image 2 onto the car in image 1"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'
    
レスポンス例
{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": [
                        {
                            "image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ],
                    "role": "assistant"
                }
            }
        ],
        "finished": true
    },
    "usage": {
        "image_count": 1,
        "input_tokens": 10867,
        "output_tokens": 2,
        "size": "1488*704",
        "total_tokens": 10869
    },
    "request_id": "71dfc3c6-f796-9972-97e4-bc4efc4faxxx"
}

非同期呼び出し

重要

DashScope Python SDK のバージョンが 1.25.15 以降、DashScope Java SDK のバージョンが 2.22.13 以降であることを確認してください。

Python

リクエスト例

import os
import base64
import mimetypes
import urllib.request
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus

# 以下はシンガポールリージョンの base_url です。base_url はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- Base64 エンコーディング関数 ---
# 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}"

"""
画像入力方法:
以下に 3 つの画像入力方法が提供されています。いずれか 1 つを選択してください。
1. パブリック URL を使用 - パブリックにアクセス可能な画像に適しています。
2. ローカルファイルを使用 - ローカルでの開発およびテストに適しています。
3. Base64 エンコーディングを使用 - プライベート画像や暗号化された伝送が必要なシナリオに適しています。
"""
# [方法 1] パブリック画像 URL を使用
image_1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"
image_2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"

# [方法 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
# image_1 = "file:///path/to/your/car.png"
# image_2 = "file:///path/to/your/paint.png"

# [方法 3] Base64 エンコードされた画像を使用
# image_1 = encode_file("/path/to/your/car.png")
# image_2 = encode_file("/path/to/your/paint.png")

# 非同期タスクを作成します。
def create_async_task():
    print("Creating async task...")
    message = Message(
        role="user",
        content=[
            {"text": "Spray the graffiti from image 2 onto the car in image 1."},
            {"image": image_1},
            {"image": image_2},
        ],
    )
    response = ImageGeneration.async_call(
        model="wan2.7-image-pro",
        api_key=api_key,
        messages=[message],
        watermark=False,
        n=1,
        size="2K",  # wan2.7-image-pro は、テキストからの画像生成シナリオでのみ 4K 解像度をサポートします。画像編集とコラージュ生成は最大 2K 解像度をサポートします。
    )

    if response.status_code == 200:
        print("Task created successfully:", response)
        return response
    else:
        raise Exception(f"Failed to create task: {response.code} - {response.message}")

# タスクの完了を待ちます。
def wait_for_completion(task_response):
    print("Waiting for task completion...")
    status = ImageGeneration.wait(task=task_response, api_key=api_key)

    if status.output.task_status == "SUCCEEDED":
        print("Task succeeded!")
        # 結果の画像 URL を抽出し、画像をローカルファイルに保存します。
        for i, choice in enumerate(status.output.choices):
            for j, content in enumerate(choice["message"]["content"]):
                if content.get("type") == "image":
                    image_url = content["image"]
                    file_name = f"output_{i}_{j}.png"
                    # 結果の URL は 24 時間有効です。速やかに画像をダウンロードしてください。
                    urllib.request.urlretrieve(image_url, file_name)
                    print(f"Image saved to {file_name}")
    else:
        raise Exception(f"Task failed with status: {status.output.task_status}")

# 非同期タスクに関する情報を取得します。
def fetch_task_status(task):
    print("Fetching task status...")
    status = ImageGeneration.fetch(task=task, api_key=api_key)

    if status.status_code == HTTPStatus.OK:
        print("Task status:", status.output.task_status)
        print("Response details:", status)
    else:
        print(f"Failed to fetch status: {status.code} - {status.message}")

# 非同期タスクをキャンセルします。
def cancel_task(task):
    print("Canceling task...")
    response = ImageGeneration.cancel(task=task, api_key=api_key)

    if response.status_code == HTTPStatus.OK:
        print("Task canceled successfully:", response.output.task_status)
    else:
        print(f"Failed to cancel task: {response.code} - {response.message}")

# メインの実行フロー。
if __name__ == "__main__":
    task = create_async_task()
    wait_for_completion(task)

レスポンス例

  1. タスク作成のレスポンス例

    {
        "status_code": 200,
        "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
        "code": "",
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": null,
            "audio": null,
            "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
            "task_status": "PENDING"
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "characters": 0
        }
    }
  2. タスク結果のクエリに対するレスポンス例

    URL は 24 時間有効です。速やかに画像をダウンロードしてください。
    {
        "status_code": 200,
        "request_id": "3b99aae5-d26f-9059-8dd0-ee9ca4804xxx",
        "code": null,
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "audio": null,
            "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
            "task_status": "SUCCEEDED",
            "submit_time": "2026-03-31 22:58:47.646",
            "scheduled_time": "2026-03-31 22:58:47.683",
            "end_time": "2026-03-31 22:58:59.642",
            "finished": true
        },
        "usage": {
            "input_tokens": 18711,
            "output_tokens": 2,
            "characters": 0,
            "size": "2985*1405",
            "total_tokens": 18713,
            "image_count": 1
        }
    }

Java

リクエスト例

import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * wan2.7-image-pro 画像編集 - 非同期呼び出しの例
 */
public class Main {

    static {
        // 以下はシンガポールリージョンの URL です。base_url はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:apiKey="sk-xxx"
    // API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // --- Base64 エンコーディング関数 ---
    // Base64 エンコーディング形式は data:{MIME_type};base64,{base64_data} です
    public static String encodeFile(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(Paths.get(filePath));
        return "data:" + mimeType + ";base64," + base64String;
    }

    public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException, IOException {
        /*
         * 画像入力方法の説明:
         * 以下に 3 つの画像入力方法が提供されています。いずれか 1 つを選択できます。
         * 1. パブリック URL を使用 - パブリックにアクセス可能な画像に適しています。
         * 2. ローカルファイルを使用 - ローカルでの開発およびテストに適しています。
         * 3. Base64 エンコーディングを使用 - プライベート画像を含むシナリオや、暗号化された伝送が必要なシナリオに適しています。
         */
        // [方法 1] パブリック画像 URL を使用
        String image1 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp";
        String image2 = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp";

        // [方法 2] ローカルファイルを使用 (絶対パスと相対パスをサポート)
        // 必須フォーマット:file:// + ファイルパス
        // String image1 = "file:///path/to/your/car.png";
        // String image2 = "file:///path/to/your/paint.png";

        // [方法 3] Base64 エンコードされた画像を使用
        // String image1 = encodeFile("/path/to/your/car.png");
        // String image2 = encodeFile("/path/to/your/paint.png");

        // マルチ画像入力メッセージを構築
        ImageGenerationMessage message = ImageGenerationMessage.builder()
                .role("user")
                .content(Arrays.asList(
                        // マルチ画像入力をサポートしています。複数の参照画像を提供できます。
                        Collections.singletonMap("text", "Spray-paint the graffiti from image 2 onto the car in image 1"),
                        Collections.singletonMap("image", image1),
                        Collections.singletonMap("image", image2)
                )).build();

        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.7-image-pro")
                .n(1)
                .size("2K") // wan2.7-image-pro モデルは、テキストからの画像生成でのみ 4K 解像度をサポートします。画像編集と合成画像生成では、最大 2K 解像度がサポートされます。
                .messages(Arrays.asList(message))
                .build();

        ImageGeneration imageGeneration = new ImageGeneration();
        ImageGenerationResult result = null;
        try {
            System.out.println("---async call for image editing, creating task----");
            result = imageGeneration.asyncCall(param);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("Task creation result:");
        System.out.println(JsonUtils.toJson(result));

        String taskId = result.getOutput().getTaskId();
        // タスクの完了を待機
        waitTask(taskId);
    }

    public static void waitTask(String taskId) throws ApiException, NoApiKeyException, IOException {
        ImageGeneration imageGeneration = new ImageGeneration();
        System.out.println("\n---waiting for task completion----");
        ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
        // 結果の画像 URL を取得し、ローカルファイルに保存
        for (int i = 0; i < result.getOutput().getChoices().size(); i++) {
            List<Map<String, Object>> contents = result.getOutput().getChoices().get(i)
                    .getMessage().getContent();
            for (int j = 0; j < contents.size(); j++) {
                if ("image".equals(contents.get(j).get("type"))) {
                    String imageUrl = (String) contents.get(j).get("image");
                    String fileName = "output_" + i + "_" + j + ".png";
                    // 結果の URL は 24 時間有効です。速やかに画像をダウンロードしてください。
                    try (InputStream in = new URL(imageUrl).openStream()) {
                        Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
                    }
                    System.out.println("Image saved to " + fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        asyncCall();
    }
}

レスポンス例

  1. タスク作成のレスポンス例

    {
        "requestId": "ccf4b2f4-bf30-9e13-9461-3a28c6a7bxxx",
        "output": {
            "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
            "task_status": "PENDING"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
  2. タスク結果のクエリに対するレスポンス例

    URL は 24 時間有効です。速やかに保存してください。
    {
        "requestId": "60a08540-f1c1-9e76-8cd3-d5949db8cxxx",
        "usage": {
            "input_tokens": 18711,
            "output_tokens": 2,
            "total_tokens": 18713,
            "image_count": 1,
            "size": "2985*1405"
        },
        "output": {
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "task_id": "8811b4a4-00ac-4aa2-a2fd-017d3b90cxxx",
            "task_status": "SUCCEEDED",
            "finished": true,
            "submit_time": "2026-03-31 19:57:58.840",
            "scheduled_time": "2026-03-31 19:57:58.877",
            "end_time": "2026-03-31 19:58:11.563"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }

curl

ステップ 1:タスクを作成してタスク ID を取得

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header "X-DashScope-Async: enable" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
                        {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
                        {"text": "Spray-paint the graffiti from image 2 onto the car in image 1"}
                    ]
                }
            ]
        },
        "parameters": {
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'
    

レスポンス例

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

ステップ 2:タスク ID で結果をクエリ

前のステップで取得した task_id を使用して、API を通じてタスクステータスをポーリングし、task_status が SUCCEEDED または FAILED になるまで続けます。

{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。task_id は 24 時間クエリに有効です。

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

レスポンス例

画像 URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
    "request_id": "810fa5f5-334c-91f3-aaa4-ed89cf0caxxx",
    "output": {
        "task_id": "a81ee7cb-014c-473d-b842-76e98311cxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-03-26 17:16:01.663",
        "scheduled_time": "2026-03-26 17:16:01.716",
        "end_time": "2026-03-26 17:16:22.961",
        "finished": true,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-xxx.oss-xxx.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "size": "2976*1408",
        "total_tokens": 11017,
        "image_count": 1,
        "output_tokens": 2,
        "input_tokens": 11015
    }
}

wan2.5-i2i-preview は、異なる API エンドポイントとパラメーターを使用します。

wan2.5-i2i-preview の呼び出し例を表示するにはクリック

同期呼び出し

重要

DashScope Python SDK のバージョンが 1.25.2 以上、DashScope Java SDK のバージョンが 2.22.2 以上であることを確認してください。

古い SDK バージョンでは「url error, please check url!」エラーが発生する可能性があります。SDK をインストールまたはアップグレードしてください。

Python

この例では、パブリック URL、Base64 エンコーディング、ローカルファイルパスの 3 つの画像入力方法をサポートしています。

リクエスト例
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

# 次の URL はシンガポールリージョン用です。WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# 環境変数を設定していない場合は、次の行を置き換えてください:api_key="sk-xxx"
# API キーはシンガポールと北京で異なります。API キーを取得する:https://www.alibabacloud.com/help/ja/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# --- 入力画像:Base64 エンコーディング ---
# 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 エンコーディング — プライベート画像や安全な伝送に最適
"""

# [方法 1] パブリック画像 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"

# [方法 2] ローカルファイル (絶対パスと相対パスをサポート)
# 形式:file:// + ファイルパス
# 例 (絶対パス):
# image_url_1 = "file://" + "/path/to/your/image_1.png"     # Linux/macOS
# image_url_2 = "file://" + "C:/path/to/your/image_2.png"  # Windows
# 例 (相対パス):
# image_url_1 = "file://" + "./image_1.png"                 # パスを調整してください
# image_url_2 = "file://" + "./image_2.png"                # パスを調整してください

# [方法 3] Base64 エンコードされた画像
# image_url_1 = encode_file("./image_1.png")               # パスを調整してください
# image_url_2 = encode_file("./image_2.png")              # パスを調整してください

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 beside 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:
    # 画像を現在のディレクトリに保存
    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))
レスポンス例
画像 URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
    "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 beside 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 clock facing the camera and parallel to the tabletop, with natural shadow projection."
            }
        ],
        "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

この例では、パブリック URL、Base64 エンコーディング、ローカルファイルパスの 3 つの画像入力方法をサポートしています。

リクエスト例
// 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 {
        // 次の URL はシンガポールリージョン用です。WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行を置き換えてください:apiKey="sk-xxx"
    // API キーはシンガポールと北京で異なります。API キーを取得する:https://www.alibabacloud.com/help/ja/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    /**
     * 画像入力方法:いずれかを選択
     *
     * 1. パブリック URL — パブリックにアクセス可能な画像に最適
     * 2. ローカルファイル — ローカルでの開発とテストに最適
     * 3. Base64 エンコーディング — プライベート画像や安全な伝送に最適
     */

    // [方法 1] パブリック 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";

    // [方法 2] ローカルファイルパス (file://+絶対パス または file:///+絶対パス)
    // 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

    // [方法 3] Base64 エンコーディング
    // static String imageUrl_1 = encodeFile("/your/path/to/image_1.png");
    // static String imageUrl_2 = encodeFile("/your/path/to/image_2.png");

    // 編集する画像のリスト
    static List<String> imageUrls = new ArrayList<>();
    static {
        imageUrls.add(imageUrl_1);
        imageUrls.add(imageUrl_2);
    }

    public static void syncCall() {
        // パラメーターを設定
        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 beside 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));
    }

    /**
     * ファイルを 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("File not found: " + filePath);
        }
        // MIME タイプを検出
        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");
        }
        // ファイルを読み込んでエンコード
        byte[] fileBytes = null;
        try{
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read file: " + filePath);
        }

        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void main(String[] args) {
        syncCall();
    }
}
レスポンス例
画像 URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
    "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 beside 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 clock facing the camera and 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
    }
}

非同期呼び出し

重要

DashScope Python SDK のバージョンが 1.25.2 以上、DashScope Java SDK のバージョンが 2.22.2 以上であることを確認してください。

古い SDK バージョンでは「url error, please check url!」エラーが発生する可能性があります。SDK をインストールまたはアップグレードしてください。

Python

この例では、パブリック URL を使用して画像を渡します。

リクエスト例

import os
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import dashscope
import requests
from dashscope import ImageSynthesis

# 次の URL はシンガポールリージョン用です。WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# 環境変数を設定していない場合は、次の行を置き換えてください:api_key="sk-xxx"
# API キーはシンガポールと北京で異なります。API キーを取得する:https://www.alibabacloud.com/help/ja/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# パブリック画像 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)


# 非同期タスクを作成
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 beside 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


# 非同期タスクの終了を待機
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)
        # ファイルを現在のディレクトリに保存
        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))


# 非同期タスクのステータスを取得
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))


# 非同期タスクをキャンセル。PENDING 状態のタスクのみキャンセル可能。
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()

レスポンス例

1. タスク作成時のレスポンス

{
	"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. タスク結果クエリ時のレスポンス

画像 URL は 24 時間で有効期限が切れます。速やかに画像をダウンロードしてください。
{
    "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 beside 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 clock facing the camera and parallel to the tabletop, with natural shadow projection."
            }
        ],
        "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

この例では、デフォルトでパブリック URL を使用して画像を渡します。

リクエスト例

// 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 {
        // 次の URL はシンガポールリージョン用です。WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // 環境変数を設定していない場合は、次の行を置き換えてください:apiKey="sk-xxx"
    // API キーはシンガポールと北京で異なります。API キーを取得する:https://www.alibabacloud.com/help/ja/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // パブリック 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";

    // 編集する画像のリスト
    static List<String> imageUrls = new ArrayList<>();
    static {
        imageUrls.add(imageUrl_1);
        imageUrls.add(imageUrl_2);
    }

    public static void asyncCall() {
        // パラメーターを設定
        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 beside 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();
        // DASHSCOPE_API_KEY が環境変数として設定されている場合、apiKey は空にできます。
        ImageSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }


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

レスポンス例

1. タスク作成時のレスポンス

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

2. タスク結果クエリ時のレスポンス

画像 URL は 24 時間で有効期限が切れます。速やかに画像をダウンロードしてください。
{
    "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 beside 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 clock facing the camera and 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
    }
}

curl

これは 2 段階のプロセスです:タスクを作成し、次に結果を取得します。

説明
  • 非同期呼び出しの場合、ヘッダーパラメーター X-DashScope-Asyncenable に設定します。

  • 非同期タスクの task_id は 24 時間有効です。有効期限が切れると、タスクのステータスは UNKNOWN になります。

ステップ 1:タスクを作成するためのリクエストを送信

このリクエストはタスク ID (task_id) を返します。

リクエスト例
 curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.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 beside 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
    }
}'

レスポンス例

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

ステップ 2:タスク ID で結果をクエリ

前のステップで取得した task_id を使用して、API を通じてタスクステータスをポーリングし、task_status が SUCCEEDED または FAILED になるまで続けます。

リクエスト例

{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。task_id は 24 時間クエリに有効です。

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

レスポンス例

画像 URL は 24 時間有効です。速やかに画像をダウンロードしてください。
{
    "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": "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,
            "FAILED": 0,
            "SUCCEEDED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

モデルの選択

  • wan2.7-image-pro および wan2.7-image (推奨):精密な編集や複数の整合性のある画像の生成に最適です。

    • 精密な局所編集:特定の領域を選択して要素を移動、置換、または追加します。e コマースのレタッチやデザイン調整に最適です。

    • マルチパネル生成:1 回の呼び出しで複数のスタイルが統一された画像を生成します。コミックの絵コンテや製品シリーズに最適です。

  • wan2.6-image:テキスト/画像の混合または複数の参照を使用した様式化された編集。画像内にテキストを生成し、最大 4 つの参照画像を受け入れます。

  • wan2.5-i2i-preview:単純な画像編集やマルチ画像融合に適しています。

各モデルの入出力仕様については、入力画像の仕様および出力画像の解像度をご参照ください。

デモギャラリー

画像から画像セットへ

入力画像

出力画像

East Asian male portrait, 20 years old, curly medium-length hair, artistic temperament

output

wan_image_reqid_57d7a71c-1932-4de8-8c32-be0f3fd5696f_n1-2026-03-31-19-32-44

output

プロンプトを表示するにはクリック

ケース 1:写真撮影

基本キャラクター設定:20 歳の東アジア人男性、ミディアムレングスのカーリーヘア、芸術的な雰囲気、はっきりとした顔立ち、繊細な目。シンプルな白い T シャツまたは水色のシャツを着用し、若々しく自然な雰囲気を醸し出している。
1. 民国時代の学者スタイル
プロンプト:
[基本顔記述] キャラクターの外見は参照画像 1 に基づき、濃いシアンの長袍と丸い金縁の眼鏡をかけ、扇子を持っている。背景は古い上海の書斎で、木製の本棚、温かみのある黄色のトーン、レトロなフィルムの質感、柔らかなサイドライト、光線の中で舞う埃があり、文化的で静かな雰囲気を醸し出している。ハッセルブラッド中判、85mm レンズ、高解像度、映画的なカラーグレーディング、ウォン・カーウァイスタイル。
小道具:扇子 / 糸綴じの本 / 丸眼鏡
色調:温かい黄色 / 濃いシアン / セピア
2. 英国紳士スタイル
プロンプト:
[基本顔記述] キャラクターの外見は参照画像 1 に基づき、濃い灰色のツイードの三つ揃いのスーツとヴィンテージの機械式時計を身に着け、赤ワインのグラスを持ってそれを見つめている。背景はクラシックな図書館またはプライベートクラブで、濃い革のソファ、レンブラント照明、暗くエレガントで高貴な雰囲気。彼はクールな視線を持ち、豊かなディテールとクリアなテクスチャで、英国貴族の気質を醸し出している。8k 解像度、ファッション雑誌風のショット。
小道具:ワイングラス / パイプ / 機械式時計
色調:濃い灰色 / バーガンディ / ダークゴールド
3. 90 年代香港レトロスタイル
プロンプト:
[基本顔記述] キャラクターの外見は参照画像 1 に基づき、ウォッシュドデニムジャケットまたは花柄のシャツを着用し、少し乱れた髪で腕を組んでいる。背景は夜のネオンサインのある通りで、ぼやけた光の点、高い粒子感、豊かな色彩が特徴で、赤と青の色彩の衝突がある。ウォン・カーウァイスタイル、感情的で、夢見るような視線、直接フラッシュ効果、ノスタルジックな雰囲気。[全身ショット]。
色調:ネオンレッド / ダークブルー / フィルムグリーン
4. 新中式禅スタイル
プロンプト:
[基本顔記述] キャラクターの外見は参照画像 1 に基づき、歯を見せて少し微笑み、改良された白い中国風スタンドカラーシャツを着用し、梅の枝を持っている。背景はミニマリストな空白の壁または竹林で、太陽光が壁にまだらな影を落としている。色調はクールで静かで、東洋の美学を体現している。肌は半透明で、高い粒子感とマットな仕上がり。構図はシンプルで、光と影の層が豊か。ハイエンドな写真、禅の雰囲気。
小道具:梅の枝
色調:白 / 濃い緑 / 明るい灰色
5. ヴィンテージアーティストスタイル
プロンプト:
[基本顔記述] キャラクターの外見は参照画像 1 に基づき、ペンキで汚れた白いシャツと茶色の革のエプロンを着用し、絵筆またはパレットを持っている。背景は明るい光とカラフルな光と影のあるきれいなスタジオ。彼は集中した表情で、手の中のペンキを見ており、カメラを見ていない。髪は少し乱れ、芸術的な雰囲気、印象派の色調、強い質感がある。
小道具:絵筆 / パレット / スケッチブック
色調:温かい光 / カラフルなペンキ / 茶色
6. クラシックノワール白黒スタイル
プロンプト:
[基本顔記述] キャラクターの外見は参照画像 1 に基づき、黒のタートルネックセーターを着用し、タバコを持ち、黒のフェドラ帽をかぶっている。背景は影が交差する階段または廊下。高コントラストの白黒写真、硬い照明、強い影、ミステリー感、ハードボイルドな探偵スタイル。顔の輪郭はシャープで、肌の質感が非常にクリア。クラシックな映画のスチル写真、時代を超えた感覚、横顔のクローズアップ、芸術的な写真。
小道具:杖 / フェドラ帽 / サングラス
色調:白黒 / 高コントラスト

ケース 2:ビジュアルデザイン

画像 1:商業グレードの製品写真のメインビジュアルカバー画像、正面からのパノラマ構図。レトロフューチャーなワイヤレスオーバーイヤーヘッドホンが幾何学的な石膏の形状の上に浮かび、完璧な対称美を披露している。素材はシャンパンゴールドの金属とクリームホワイトのシェル。背景は深くぼかされた温かい室内の光と影で、柔らかな光が製品のシルエットを縁取っている。画像内の空白が強い呼吸感を生み出し、静かな聴覚体験を示唆している。8k 超高解像度、ミニマリストでプレミアムな感覚。
画像 2:製品の素材ディテールの 100mm マクロショットで、ヘッドホンの伸縮アームの接続部に焦点を当てている。シャンパンゴールドのブラッシュドアルミニウム合金の質感と CNC 精密カットの面取りがはっきりと見える。鋭い逆光が金属のエッジにスターバーストハイライトを作り出している。背景は暗く、金属の工業的な精密さを強調している。画質は非常にシャープでノイズがない。
画像 3:素材の極端なクローズアップマクロショットで、モカ色のプロテインレザーイヤーカップの表面に焦点を当てている。サイドライトが革の微細な毛穴の質感、押したときの柔らかなしわ、通気孔のディテールを明らかにし、究極の肌に優しい快適さと弾力性を伝えている。光と影は層が豊かで、色調は温かくしっとりしている。超高精細マクロ写真。
画像 4:製品の芸術的な分解図で、レトロフューチャーなヘッドホンの内部サウンドユニット、ノイズキャンセリングチップ、バッテリーモジュール、外部のウォールナットウッド装飾パネル、金属フレームが浮遊し、分解された状態で表示されている。背景は深いテックブルーで、内部コンポーネントは半透明のホログラフィックな技術的質感を持ち、内部の精密な職人技と現代技術の組み合わせを強調している。ハイテクな商業ポスタースタイル。
画像 5:装着シーンの 35mm 人文ショットで、モデルの顎のラインと首にクローズアップし、シャンパンゴールドのヘッドホンの完璧なフィット感を示している。横後方からの自然な温かい夕日の光がリムライトを作り出し、髪の端が金色に輝いている。モデルの肌の色は健康的で自然な質感を持ち、リラックスした没入型の音楽鑑賞ライフスタイル感を醸し出している。背景はぼやけた家庭環境。
画像 6:建築的な光と影に敬意を表した静物写真。ヘッドホンはミニマリストな灰色のコンクリートテーブルの上に置かれている。午後の太陽光がブラインドを通して差し込み、マットなクリームホワイトのボディとシャンパンゴールドのフレームを横切る縞模様の硬い影を落とし、光と闇の強い幾何学的な構成を作り出している。これにより、ボディの立体的な形状と素材の対比が強調されている。クールとウォームの色調の衝突、ミニマリストな構図。
画像 7:カラーオプションを示すトップダウンのフラットレイ構図。シルバーホワイト、ブラックゴールド、ブルーカッパーの異なる配色を持つシリーズの 3 つのヘッドホンが並べて配置されている。背景は質感の高い灰色のウールフェルト布。柔らかなトップライトが CMF デザインの多様性と素材の繊細な手触りを強調している。画像は清潔で整然としており、デザイン雑誌のスタイル。
画像 8:ブランドのライフスタイルファミリーポートレート静物写真。レトロフューチャーなヘッドホンが、それに合う精巧なレザーケースの隣に置かれている。テーブルの上にはビニールレコードプレーヤー、回転するビニールレコード、湯気の立つコーヒーカップがある。背景は温かいアンビエント照明でレンダリングされ、深いウォールナットウッドのトーンが支配的で、スローペースなライフスタイルと高忠実度の音質を組み合わせたブランド哲学を伝えている。映画的な物語性のある照明。

インタラクティブ編集

入力画像

出力画像

image (20)-2026-03-31-19-17-37

image (21)-2026-03-31-19-17-37

画像 1 に基づいて編集します。ボックス 1 で選択されたラズベリーをレモンに、ボックス 2 のラズベリーをイチゴに、ボックス 3 のラズベリーをブルーベリーに置き換えます。結果は元の画像と調和するように統合され、参照ボックスと数字は含めず、残りのコンテンツは変更しないでください。

5eecdaf48460cde5f7fd58249809b192a118accde85283f275b8339e1c4c24831b75b38faadcd24bec177c308ebd5304463ca8e345548eb5f551b6ba01cd2c8d2d9b5606fa569ff7ba4077816ac9b801464f65aedbcf494f4fb4c8ed7016461c-combine

5eecdaf48460cde5f7fd58249809b192a118accde85283f275b8339e1c4c24831b75b38faadcd24bec177c308ebd530460436714d0283cee289325430893028097a53a8e5d630fb1c2d4c85d8cbb68a4387575c4b03700344fb4c8ed7016461c-2026-03-31-19-13-38

画像 1 から選択したパターンを画像 2 の選択した領域に配置します。

マルチ画像融合

入力画像

出力画像

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304e9d05d028a65a9ac270ee730e44b8c75c6634a9b9a7a70240d438b02b2f2153dc68966b442378d1d4fb4c8ed7016461c-combine

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd53044b9a1d72dee2f8507ee704b9cef3832907ff1182f52507c9bc4737520762d46a722e658f57cda6524fb4c8ed7016461c-2025-12-29-19-11-31

画像 1 の少年と画像 2 の犬のポートレートを撮影します。少年は犬を抱きしめており、二人ともとても幸せそうです。スタジオの柔らかな照明、青いテクスチャの背景。

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304f060ec7a363e318af9bfaaa5e07be972cfc1ea4e21b47637fcdb2dfc53130c40a8efed5defc408a04fb4c8ed7016461c-combine

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304922cbdef3e3c42f83239de6d0f35a8b76f0e38934cc5170f7a908ec12140fb0af6590c72bcf1ba6f4fb4c8ed7016461c-2025-12-29-19-15-53

画像 1 のドレスを画像 2 の鳥の色を使って再配色します。芸術的にしますが、ドレスのスタイルとモデルは変更しないでください。

被写体の特徴維持

入力画像

出力画像

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304448a972b9f2ee7a7aadcc61495f4975a049f009e7721cbc833dc3a8005b1b026a54eaaec109d73484fb4c8ed7016461c-2025-12-29-20-00-21

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304cc1b4a509823c5fb5e60999898811f8b51d7419220a118c9ff82110bc9525725a9ad7338f75985794fb4c8ed7016461c-2025-12-29-20-00-21

「季節の移り変わり」をテーマにしたポラロイド写真 4 枚セットを生成してください。各写真は公園の木の下の同じ場所で撮影されていますが、それぞれ春、夏、秋、冬の風景を示しています。人物の服装も季節に合わせてください:春は薄手のジャケット、夏は半袖シャツ、秋はトレンチコート、冬はマフラーと厚手のコート。この写真セットをダイニングテーブルの上に置いてください。

検出とセグメンテーション

入力画像

出力画像

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304b025e74206dc2cec5c2e587c3fe6fb135293836c9479220355470da15476dc934b26018061e9db0b4fb4c8ed7016461c-2025-12-29-19-54-33

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd530451385eb561b49b0fe1f2169526b6a7e15bd78940def3c640c801511c349f6df35dceb72f4d3755f94fb4c8ed7016461c-2025-12-29-19-54-33

画像内のラップトップと目覚まし時計を検出し、バウンディングボックスを描画し、「laptop」と「clock」とラベル付けします。

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd530440256f9add4113787af5d4f3a55469b38ef2422f018076640eb7cb552584c02ee729fcb23fec3bca4fb4c8ed7016461c-2025-12-29-19-54-33

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304f0612d67f5c810ebef958385624ebd17323047aa5d00465d0e35257de5a2ea49d4b375d2e57693fa4fb4c8ed7016461c-2025-12-29-19-54-32

画像内のガラスカップをセグメント化します。

要素の抽出

入力画像

出力画像

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd53046b83761f1ab18c40e144f5db2b388e5f865ba9a5961d98b2710ce177c6a0f4baff63fe52259c44364fb4c8ed7016461c-2025-12-29-19-48-27

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd53048e2a0d1d2805d92ba8d45a3bd1368528dd76f517b21ad1f545eb4097610838497cbdb5196da94ff54fb4c8ed7016461c-2025-12-29-19-48-27

アップロードされた写真から衣料品を抽出し、純白の背景に平置きで配置します。リアルなディテールと素材の質感を維持します。ファッション e コマーススタイルで、衣料品のディスプレイに適しています。

テキスト編集

入力画像

出力画像

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd530490f493eca22f34f0197173ddfdef17a04b34cb94813178b9d4eee36d246d3530a3e2fc6258cca0694fb4c8ed7016461c-2025-12-29-19-28-35

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304fe77776567f4ef79cb621289a6fdaa981f3364fe4c7c56265403b5d9d5ac43eaf5931f62db14952f4fb4c8ed7016461c-2025-12-29-19-28-35

画像からすべてのウォーターマークを削除します。

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd530476e971380812b1b9dbeac68272a27057175499fe84f0781c7b6fa6535f438c67f3556acc8c7324394fb4c8ed7016461c-2025-12-29-19-28-35

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd53047be52c6f41edecdefa77f0d93335d1492f1821b47dff7a1b08f60e99bdafcc84c31e3658fc593c904fb4c8ed7016461c-2025-12-29-19-28-35

砂の上に手で「Time for Holiday?」とさりげなく書きます。

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304fdb284f8d5c8ead814d11890da1a49411a6d9d41ad1bb2a4bf0b93d0bee5d792e8f5b419a3da9d534fb4c8ed7016461c-2025-12-29-19-28-34

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304df1c8787530497f4cc3bee0b84d3ba51d0353fceb8d0518ded6a25e8c0ddfec714f719154ac1c9354fb4c8ed7016461c-2025-12-29-19-28-34

18 を 29 に、JUNE を SEPTEMBER に変更します。

カメラと視点の編集

入力画像

出力画像

image (2)-2025-12-29-19-42-44

image (3)-2025-12-29-19-42-44

人物の特徴を変えずに、正面、側面、背面のビューを生成します。

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd5304a53988b2efdd2fb6b95cb3b1b02701e6ff2c4902170b1ee230a9b4e3726a891c93646d68b821de294fb4c8ed7016461c-2025-12-29-19-42-43

5eecdaf48460cde5544f9fac410016bc2fe4c1b4d23666c075b8339e1c4c24831b75b38faadcd24bec177c308ebd530428783dee341e41eb06234dfb75bd149d774f4850000123559a98bcd7ece97dc4a6c3cefa983ae8ac4fb4c8ed7016461c-2025-12-29-19-42-43

この写真を魚眼レンズで再撮影します。

入力仕様

入力画像の仕様

仕様

wan2.7-image-pro, wan2.7-image

wan2.6-image

wan2.5-i2i-preview

入力画像数

0 から 9 (0 はテキストからの画像生成モードに対応)

画像編集:1 から 4 / テキストと画像の混合:0 から 1

1 から 3

画像フォーマット

JPEG、JPG、PNG (アルファチャンネルは非対応)、BMP、WEBP

JPEG、JPG、PNG (アルファチャンネルは非対応)、BMP、WEBP

JPEG、JPG、PNG (アルファチャンネルは非対応)、BMP、WEBP

画像の幅と高さの範囲

[240, 8000] ピクセル

[240, 8000] ピクセル

[384, 5000] ピクセル

ファイルサイズ

≤ 20 MB

≤ 10 MB

≤ 10 MB

アスペクト比

[1:8, 8:1]

無制限

[1:4, 4:1]

画像入力順序

プロンプト内の画像番号は配列の位置に対応します:最初の画像は「画像 1」、2 番目は「画像 2」です。「[image 1]」や「[image 2]」のようなマーカーも使用できます。

{
    "content": [
        {"text": "編集指示、例:画像 1 の目覚まし時計を画像 2 の食卓の花瓶の隣に置く"},
        {"image": "https://example.com/image1.png"},
        {"image": "https://example.com/image2.png"}
    ]
}

入力画像

出力画像

image (19)-转换自-png

画像 1

image (20)-转换自-png

画像 2

04e0fc39-7ad6-41e0-9df9-1f69ac3ce825-转换自-png

プロンプト:画像 1 を画像 2 に移動

36ed450d-bd54-4169-b13f-3d0f26d9d360-转换自-png

プロンプト:画像 2 を画像 1 に移動

画像入力方法

以下のいずれかの方法で画像を渡します:

方法 1:パブリック URL

  • パブリックにアクセス可能な HTTP または HTTPS 画像 URL を提供します。

  • 値の例:https://xxxx/img.png

  • 画像が OSS またはパブリックな画像ホスティングサービスでホストされている場合に使用します。

方法 2:Base64 エンコーディング

画像ファイルを Base64 エンコードされた文字列に変換し、次の形式でフォーマットします:data:{MIME_type};base64,{base64_data}

  • 値の例:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDg...... (長さの制限によりスニペットです)。呼び出し時には、完全な文字列を渡してください。

  • {base64_data}:画像ファイルの Base64 エンコードされた文字列。

  • {MIME_type}:画像のメディアタイプ。ファイル形式に対応している必要があります。

    画像フォーマット

    MIME タイプ

    JPEG

    image/jpeg

    JPG

    image/jpeg

    PNG

    image/png

    BMP

    image/bmp

    WEBP

    image/webp

  • ローカル、プライベート、または暗号化された画像伝送に使用します。

コード例:画像の Base64 エンコーディング

import os
import base64
import mimetypes

# 形式は data:{mime_type};base64,{base64_data} です
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    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}"
        
        
# エンコーディング関数を呼び出します。"/path/to/your/image.png" をローカル画像ファイルのパスに置き換えないと、コードは実行されません。
image = encode_file("/path/to/your/image.png")

方法 3:ローカルファイルパス (SDK のみ)

  • Python SDK絶対パスと相対パスの両方をサポートします。ファイルパスのルールは以下の通りです:

    システム

    入力ファイルパス

    例 (絶対パス)

    例 (相対パス)

    Linux または macOS

    file://{ファイルの絶対パスまたは相対パス}

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

    file://./images/test.png

    Windows

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

    file://./images/test.png

  • Java SDK絶対パスのみをサポートします。ファイルパスのルールは以下の通りです:

    システム

    入力ファイルパス

    例 (絶対パス)

    Linux または macOS

    file://{ファイルの絶対パス}

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

    Windows

    file:///{ファイルの絶対パス}

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

  • ローカル開発での迅速なテストに使用します。

主な機能

1. 指示追従 (プロンプト)

パラメーター:messages.content.text または input.prompt (必須)、negative_prompt (オプション)。

  • text または prompt (ポジティブプロンプト):出力画像の内容、被写体、シーン、スタイル、照明、構図を記述します。

  • negative_prompt (ネガティブプロンプト):「ぼやけた」や「余分な指」など、不要なコンテンツを指定します。

パラメーター

wan2.7-image-pro, wan2.7-image

wan2.6-image

wan2.5-i2i-preview

text

必須、最大 5,000 文字

必須、最大 2,000 文字

非対応

prompt

非対応

非対応

必須、最大 2,000 文字

negative_prompt

非対応

対応、最大 500 文字

対応、最大 500 文字

2. インテリジェントなプロンプトリライトを有効にする

パラメーター:parameters.prompt_extend (bool, デフォルトは true)。

短いプロンプトを拡張して画質を向上させますが、応答時間が増加します。

ベストプラクティス:

  • 有効にする:プロンプトが簡潔または広範な場合。

  • 無効にする:細かいディテールの制御、詳細な記述、または遅延の影響を受けやすいシナリオの場合。prompt_extendfalse に設定します。

パラメーター

wan2.7-image-pro, wan2.7-image

wan2.6-image

wan2.5-i2i-preview

prompt_extend

非対応

対応 (画像編集モードのみ)

対応

3. 出力画像の解像度を設定する

パラメーター:parameters.size (string)、形式は "width*height" です。

パラメーター

wan2.7-image-pro, wan2.7-image

wan2.6-image

wan2.5-i2i-preview

size

方法 1:出力画像の解像度を指定する (推奨)

編集モード (少なくとも 1 つの画像が渡された場合) では、オプションの出力解像度ティアは 1K2K (デフォルト) です。

  • 1K:出力の総ピクセル数は 1024*1024 に近く、アスペクト比は最後の入力画像と一致します。

  • 2K:出力の総ピクセル数は 2048*2048 に近く、アスペクト比は最後の入力画像と一致します。

方法 2:生成される画像の幅と高さのピクセル値を指定する

  • 総ピクセル数は 768*768 から 2048*2048 の間で、アスペクト比の範囲は [1:8, 8:1] です。

テキストからの画像生成シナリオの wan2.7-image-pro のみ 4K 解像度をサポートします。

方法 1:入力画像の比率を参照する (推奨)

編集モード (enable_interleave=false) では、オプションの出力解像度ティアは 1K (デフォルト)、2K です。

  • 1K:出力の総ピクセル数は 1280*1280 に近く、アスペクト比は最後の入力画像と一致します。

  • 2K:出力の総ピクセル数は 2048*2048 に近く、アスペクト比は最後の入力画像と一致します。

方法 2:生成される画像の幅と高さのピクセル値を指定する

  • 総ピクセル数は 768*768 から 2048*2048 の間で、アスペクト比の範囲は [1:4, 4:1] です。

実際の出力画像のピクセル値は、指定された値に最も近い 16 の倍数になります。

生成される画像の幅と高さのピクセル値の指定のみをサポート

  • 総ピクセル数は 768*768 から 1280*1280 の間で、アスペクト比の範囲は [1:4, 4:1] です。

  • size が指定されていない場合、システムはデフォルトで総ピクセル数が 1280*1280 の画像を生成し、アスペクト比は最後の入力画像と一致します。

4. インタラクティブな精密編集

parameters.bbox_list を使用して、編集する特定の領域を選択します。wan2.7-image-pro および wan2.7-image のみでサポートされています

  • リストの長さ:入力画像の数と一致する必要があります。編集が不要な画像には空のリスト [] を使用します。

  • 座標形式:[x1, y1, x2, y2] (左上の x、左上の y、右下の x、右下の y)。座標は絶対ピクセル値で、原点 (0, 0) は左上、x 軸は右、y 軸は下です。

  • 数量制限:画像ごとに最大 2 つのバウンディングボックス。

例:3 つの入力画像があり、画像 1 には 2 つのバウンディングボックスがあり、画像 2 にはなし

[
  [[0, 0, 12, 12], [25, 25, 100, 100]],  # 画像 1 (2 つのボックス)
  [],                                    # 画像 2 (ボックスなし)
  [[10, 10, 50, 50]]                    # 画像 3 (1 つのボックス)
]

呼び出し例を表示するにはクリック

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.7-image-pro",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"image": "https://img.alicdn.com/imgextra/i3/O1CN0157XGE51l6iL9441yX_!!6000000004770-49-tps-1104-1472.webp"},
                        {"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"},
                        {"text": "Place the alarm clock from image 1 into the bounding box of image 2, and blend the scene and lighting naturally."}
                    ]
                }
            ]
        },
        "parameters": {
            "bbox_list": [[],[[989, 515, 1138, 681]]],
            "size": "2K",
            "n": 1,
            "watermark": false
        }
    }'
    

編集領域の座標を決定する方法

方法 1:OpenCV でバウンディングボックスを描画

画像上でマウスをドラッグしてバウンディングボックスを描画し、正確かつ直感的に選択します:

# 依存関係をインストール:pip install opencv-python
import cv2
import urllib.request

# サンプル画像をダウンロード (独自の画像 URL またはローカルパスに置き換えてください)
image_url = "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
urllib.request.urlretrieve(image_url, "example.webp")

# 画像を読み込み、インタラクティブウィンドウを開く
img = cv2.imread("example.webp")
# ポップアップウィンドウでマウスをドラッグしてボックスを描画します。Enter で確定、Esc でキャンセル
x, y, w, h = cv2.selectROI("Draw bounding box (Enter=confirm, Esc=cancel)", img)
cv2.destroyAllWindows()

# OpenCV が返す (x, y, w, h) を bbox_list が要求する [x1, y1, x2, y2] 形式に変換
# 座標系:原点は左上隅、x 軸は右向き、y 軸は下向き、単位はピクセル
bbox = [x, y, x + w, y + h]
print(f"Bounding box coordinates: {bbox}")  # これらの座標を parameters.bbox_list に渡す

方法 2:視覚理解モデル

qwen3.6-plus を使用して、自然言語でターゲットを記述することでターゲット領域の座標を自動的に識別します:

# 依存関係をインストール:pip install dashscope pillow
import os
import json
from dashscope import MultiModalConversation
import dashscope
from PIL import Image
import urllib.request

# 次の URL はシンガポールリージョン用です。WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"


def get_bbox_list(image, prompt):
    """
    qwen3.6-plus を使用して画像内のターゲット領域を識別し、絶対ピクセル座標を返します。

    Args:
        image: 画像 URL またはローカルパス (ローカルパス形式:"file:///absolute/path.png")
        prompt: 自然言語記述、例:「コーヒーカップ」、「皿の上のすべての果物」、「皿の中央の果物」

    Returns:
        [[x1, y1, x2, y2], ...] bbox_list に直接渡すことができる絶対ピクセル座標
    """
    # ユーザーの記述と戻り値の形式指示を連結
    full_prompt = (
        prompt + "\n"
        "上記の説明に基づいて、対応する領域の座標を返してください。\n"
        "最大 2 つの領域を返し、最も一致するターゲットを優先します。\n"
        "JSON 2D リスト形式に厳密に従ってください:[[x1, y1, x2, y2], ...]\n"
        "各座標セット:[左上の x, 左上の y, 右下の x, 右下の y]\n"
        "元の画像の絶対ピクセル座標を使用し、(0,0) を左上隅、x 軸を右向き、y 軸を下向きとします。\n"
        "領域が 1 つしかない場合でも、2D リストを使用する必要があります:[[x1, y1, x2, y2]]\n"
        "JSON リストのみを返し、他のコンテンツは返さないでください。"
    )

    messages = [
        {'role': 'user',
         'content': [
             {'image': image},
             {'text': full_prompt}
         ]}
    ]

    response = MultiModalConversation.call(
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        model='qwen3.6-plus',
        messages=messages,
    )

    text = response.output.choices[0].message.content[0]["text"]
    text = text.replace("```json", "").replace("```", "").strip()
    coords = json.loads(text)

    # モデルが 1D リスト [x1,y1,x2,y2] を返す場合を処理
    if coords and not isinstance(coords[0], list):
        coords = [coords]

    # 座標変換のために画像の寸法を取得
    if image.startswith("file://"):
        local_path = image[len("file://"):]
        img = Image.open(local_path)
    else:
        tmp_path = "temp_bbox_image"
        urllib.request.urlretrieve(image, tmp_path)
        img = Image.open(tmp_path)
    width, height = img.size

    # モデルの正規化された座標 [0, 999] を絶対ピクセル座標に変換
    bbox_list = []
    for box in coords:
        bbox_list.append([
            int(box[0] / 1000 * width),
            int(box[1] / 1000 * height),
            int(box[2] / 1000 * width),
            int(box[3] / 1000 * height)
        ])

    return bbox_list


# === 使用例 ===
image_url = "https://img.alicdn.com/imgextra/i3/O1CN01ewUWhg1eS3VqJ3wap_!!6000000003869-49-tps-2048-2048.webp"

# 名前でターゲットを選択
bbox = get_bbox_list(image_url, "coffee cup")           # [[x1, y1, x2, y2]]

# 位置記述でターゲットを選択
bbox = get_bbox_list(image_url, "the fruit in the center of the plate")  # [[x1, y1, x2, y2]]

# 領域を記述
bbox = get_bbox_list(image_url, "lavender potted plant")

# 結果は bbox_list 配列の要素として使用できます
# 注:画像ごとに最大 2 つのバウンディングボックス

課金とレート制限

  • 無料クォータと価格:モデルリストと価格

  • レート制限については、通義万相 (Wanxiang) をご参照ください。

  • 課金:

    • 正常に生成された画像ごとに料金が発生します。API が task_statusSUCCEEDED として返した場合にのみ課金されます。

    • モデルの呼び出しが失敗した場合や処理エラーが発生した場合は、料金は発生せず、無料クォータも消費されません。

API リファレンス

各モデルは異なるエンドポイントとリクエスト構造を使用します:

モデル

エンドポイント (シンガポールリージョンの例)

wan2.7-image, wan2.7-image-pro, wan2.6-image

同期 API:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

非同期 API:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

WorkspaceId を実際の ワークスペース ID に置き換えてください。

wan2.5-i2i-preview

非同期 API:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis

WorkspaceId を実際の ワークスペース ID に置き換えてください。

  • wan2.7 / wan2.6 では、messages フォーマットを使用し、messages[].content 配列の image パラメーターでイメージを、text パラメーターでプロンプトを渡します。

  • wan2.5input.images 配列で画像を、input.prompt パラメーターでプロンプトを渡します。

wan2.7-image-pro, wan2.7-image, wan2.6-image

wan2.5-i2i-preview

"input": {
    "messages": [
        {
            "role": "user",
            "content": [
                {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/pjeqdf/car.webp"},
                {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251229/xsunlm/paint.webp"},
                {"text": "Spray the graffiti from image 2 onto the car in image 1"}
            ]
        }
    ]
}
"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"
    ]
}

入出力パラメーターについては、Wan2.7 - 画像生成と編集Wan2.6 - 画像生成と編集Wanxiang – 一般画像編集 2.5 をご参照ください。