Model Wanxiang General Image Editing wan2.5 mengedit gambar atau menggabungkan beberapa gambar hanya dengan instruksi teks, sekaligus menjaga konsistensi subjek selama proses pengeditan.
Mulai cepat: Panduan pengguna
Model Studio telah merilis domain khusus ruang kerja untuk wilayah China (Beijing) dan Singapura. Domain khusus baru ini memberikan performa lebih unggul dan stabilitas lebih tinggi untuk permintaan inferensi. Kami merekomendasikan migrasi ke domain berikut:
-
China (Beijing): dari
https://dashscope.aliyuncs.comkehttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com -
Singapura: dari
https://dashscope-intl.aliyuncs.comkehttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} adalah ID ruang kerja Anda, yang dapat ditemukan di halaman Detail Ruang Kerja pada Konsol Model Studio. Domain lama tetap berfungsi sepenuhnya.
Ikhtisar model
|
Kemampuan model |
Contoh input |
Gambar output |
|
Pengeditan gambar tunggal |
|
Ganti gaun bunga dengan gaun renda bergaya vintage yang memiliki sulaman halus pada kerah dan manset. |
|
Fusi multi-gambar |
|
Letakkan jam alarm dari gambar 1 di samping vas di atas meja makan pada gambar 2. |
|
Nama model |
Deskripsi model |
Spesifikasi gambar output |
|
wan2.5-i2i-preview |
Pratinjau Wanxiang 2.5 Mendukung pengeditan gambar tunggal dan fusi multi-gambar |
Format gambar: PNG. Resolusi gambar:
|
Sebelum memanggil API, tinjau model yang didukung dan harga untuk wilayah Anda.
Prasyarat
Sebelum melakukan panggilan, dapatkan Kunci API dan ekspor Kunci API sebagai Variabel lingkungan. Untuk melakukan panggilan menggunakan SDK, instal SDK DashScope.
Wilayah China (Beijing) dan Singapura memiliki Kunci API dan titik akhir permintaan yang terpisah. Keduanya tidak dapat saling dipertukarkan. Panggilan lintas wilayah menyebabkan kegagalan otentikasi atau kesalahan layanan.
Panggilan API HTTP
Tugas pengeditan gambar memerlukan waktu untuk diselesaikan—biasanya 1 hingga 2 menit—sehingga API menggunakan pemanggilan asinkron. Alur kerja lengkap terdiri dari dua langkah inti: Buat tugas → Polling hasil.
Waktu proses aktual tergantung pada panjang antrian dan beban layanan. Tunggu hasil dengan sabar.
Langkah 1: Buat tugas dan dapatkan ID tugas
Wilayah Singapura: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis
Wilayah Beijing: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis
Ganti WorkspaceId dengan ID Ruang Kerja aktual Anda.
-
Setelah tugas dibuat, gunakan
task_idyang dikembalikan untuk menanyakan hasilnya.task_idberlaku selama 24 jam. Jangan membuat tugas duplikat. Sebagai gantinya, gunakan polling untuk mengambil hasilnya. -
Untuk panduan pemula, lihat Panggil API dengan Postman atau cURL.
Parameter permintaan |
Pengeditan gambar tunggal
Fusi multi-gambar
|
Header permintaan |
|
|
Content-Type Tipe konten permintaan. Harus berupa |
|
|
Authorization Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx. |
|
|
X-DashScope-Async Mengaktifkan pemrosesan asinkron. Permintaan HTTP hanya mendukung panggilan asinkron. Harus diatur ke Penting
Jika header permintaan ini tidak disertakan, akan dikembalikan kesalahan "current user api does not support synchronous calls". |
|
Body permintaan |
|
|
model Nama model. Untuk detailnya, lihat Model yang didukung dan harga. Nilai contoh: wan2.5-i2i-preview. |
|
|
input Informasi input dasar, seperti prompt. |
|
|
parameters Parameter pemrosesan gambar. Contohnya termasuk pengaturan resolusi, mengaktifkan penulisan ulang prompt, dan menambahkan watermark. |
Parameter respons |
Respons berhasilSimpan
Respons kesalahanPembuatan tugas gagal. Lihat 错误码.
|
|
output Informasi output tugas. |
|
|
request_id Identifikasi permintaan unik untuk pelacakan dan troubleshooting. |
|
|
code Kode kesalahan. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码. |
|
|
message Pesan kesalahan detail. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码. |
Langkah 2: Tanyakan hasil menggunakan ID tugas
Singapura
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Saat memanggil, ganti WorkspaceId dengan ID ruang kerja aktual Anda.
China (Beijing)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Saat memanggil, ganti WorkspaceId dengan ID ruang kerja aktual Anda.
-
Rekomendasi polling: Generasi gambar memakan waktu. Gunakan mekanisme polling dengan interval yang wajar, misalnya 10 detik.
-
Transisi status tugas: PENDING → RUNNING → SUCCEEDED atau FAILED.
-
Tautan hasil: Setelah tugas berhasil, URL gambar yang berlaku selama 24 jam dikembalikan. Unduh dan simpan gambar ke penyimpanan permanen, seperti OSS.
Parameter permintaan |
Hasil tugas kueriGanti Kunci API berbeda untuk setiap wilayah. Untuk informasi lebih lanjut, lihat Dapatkan Kunci API. Jika Anda menggunakan model di wilayah China (Beijing), ganti
|
Header permintaan |
|
|
Authorization Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx. |
|
Parameter jalur URL |
|
|
task_id ID tugas tersebut. |
Parameter respons |
Tugas berhasilURL gambar hanya berlaku selama 24 jam, lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan. Tugas gagalSaat tugas gagal,
Kegagalan parsialModel dapat menghasilkan beberapa gambar per tugas. Jika setidaknya satu berhasil, status tugas bernilai
Kueri tugas kedaluwarsa
|
|
output Informasi output tugas. |
|
|
usage Statistik penggunaan. Hanya menghitung hasil yang berhasil. |
|
|
request_id Identifikasi permintaan unik untuk pelacakan dan troubleshooting. |
Panggilan SDK DashScope
Nama parameter SDK sesuai dengan yang ada di panggilan API HTTP. Struktur parameter dibungkus agar sesuai dengan masing-masing bahasa pemrograman.
Karena tugas pengeditan gambar memerlukan waktu 30 hingga 60 detik, SDK membungkus alur asinkron HTTP. SDK mendukung panggilan sinkron maupun asinkron.
Waktu proses aktual tergantung pada panjang antrian dan beban layanan. Tunggu hasil dengan sabar.
Panggilan SDK Python
Pastikan versi SDK Python DashScope Anda minimal 1.25.2.
Versi lama dapat memicu kesalahan seperti “url error, please check url!”. Perbarui menggunakan Instal atau tingkatkan SDK.
Panggilan sinkron
Contoh permintaan
Contoh ini mendukung tiga metode input gambar: URL publik, pengkodean Base64, dan jalur file lokal.
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 berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. URL berbeda tiap wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key="sk-xxx"
# Kunci API berbeda antara Singapura dan Beijing. Dapatkan Kunci API: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# --- Input gambar: Pengkodean Base64 ---
# Format 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("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}"
"""
Metode input gambar:
Pilih salah satu dari berikut:
1. URL publik — terbaik untuk gambar yang dapat diakses publik
2. File lokal — terbaik untuk pengembangan dan pengujian lokal
3. Pengkodean Base64 — terbaik untuk gambar pribadi atau transmisi aman
"""
# [Metode 1] URL gambar publik
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"
# [Metode 2] File lokal (mendukung jalur absolut dan relatif)
# Format: file:// + jalur file
# Contoh (jalur absolut):
# image_url_1 = "file://" + "/path/to/your/image_1.png" # Linux/macOS
# image_url_2 = "file://" + "C:/path/to/your/image_2.png" # Windows
# Contoh (jalur relatif):
# image_url_1 = "file://" + "./image_1.png" # Sesuaikan dengan jalur Anda
# image_url_2 = "file://" + "./image_2.png" # Sesuaikan dengan jalur Anda
# [Metode 3] Gambar yang diencode Base64
# image_url_1 = encode_file("./image_1.png") # Sesuaikan dengan jalur Anda
# image_url_2 = encode_file("./image_2.png") # Sesuaikan dengan jalur Anda
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:
# Simpan gambar ke direktori saat ini
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))
Contoh respons
URL gambar kedaluwarsa setelah 24 jam. Segera unduh gambar.
{
"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
}
}
Panggilan asinkron
Contoh ini menggunakan URL publik untuk input gambar.
Contoh permintaan
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 berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. URL berbeda tiap wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key="sk-xxx"
# Kunci API berbeda antara Singapura dan Beijing. Dapatkan Kunci API: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# URL gambar publik
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)
# Buat tugas asinkron
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
# Tunggu hingga tugas asinkron selesai
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)
# Simpan file ke direktori saat ini
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))
# Ambil status tugas asinkron
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))
# Batalkan tugas asinkron. Hanya tugas dengan status PENDING yang dapat dibatalkan.
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()
Contoh respons
1. Respons saat membuat tugas
{
"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. Respons saat menanyakan hasil tugas
URL gambar kedaluwarsa setelah 24 jam. Segera unduh gambar.
{
"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
}
}
Panggilan SDK Java
Pastikan versi SDK Java DashScope Anda minimal 2.22.2.
Versi lama dapat memicu kesalahan seperti “url error, please check url!”. Perbarui menggunakan Instal atau tingkatkan SDK.
Panggilan sinkron
Contoh permintaan
Contoh ini mendukung tiga metode input gambar: URL publik, pengkodean Base64, dan jalur file lokal.
// 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 berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. URL berbeda tiap wilayah.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: apiKey="sk-xxx"
// Kunci API berbeda antara Singapura dan Beijing. Dapatkan Kunci API: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
/**
* Metode input gambar: pilih salah satu
*
* 1. URL publik — terbaik untuk gambar yang dapat diakses publik
* 2. File lokal — terbaik untuk pengembangan dan pengujian lokal
* 3. Pengkodean Base64 — terbaik untuk gambar pribadi atau transmisi aman
*/
// [Metode 1] URL publik
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";
// [Metode 2] Jalur file lokal (file://+jalur absolut atau file:///+jalur absolut)
// 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
// [Metode 3] Pengkodean Base64
// static String imageUrl_1 = encodeFile("/your/path/to/image_1.png");
// static String imageUrl_2 = encodeFile("/your/path/to/image_2.png");
// Daftar gambar untuk diedit
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void syncCall() {
// Atur parameter
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));
}
/**
* Encode file sebagai string Base64
* @param filePath Jalur file
* @return String Base64 dalam 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 not found: " + filePath);
}
// Deteksi tipe 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");
}
// Baca file dan encode
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();
}
}
Contoh respons
URL gambar kedaluwarsa setelah 24 jam. Segera unduh gambar.
{
"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
}
}
Panggilan asinkron
Contoh ini menggunakan URL publik untuk input gambar.
Contoh permintaan
// 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 berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. URL berbeda tiap wilayah.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: apiKey="sk-xxx"
// Kunci API berbeda antara Singapura dan Beijing. Dapatkan Kunci API: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// URL publik
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";
// Daftar gambar untuk diedit
static List<String> imageUrls = new ArrayList<>();
static {
imageUrls.add(imageUrl_1);
imageUrls.add(imageUrl_2);
}
public static void asyncCall() {
// Atur parameter
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();
// Jika DASHSCOPE_API_KEY diatur sebagai variabel lingkungan, apiKey bisa kosong.
ImageSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args) {
asyncCall();
}
}
Contoh respons
1. Respons saat membuat tugas
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}
2. Respons saat menanyakan hasil tugas
URL gambar kedaluwarsa setelah 24 jam. Segera unduh gambar.
{
"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
}
}
Batasan
-
Retensi data: Baik ID tugas maupun URL gambar kedaluwarsa setelah 24 jam. Anda tidak dapat menanyakan atau mengunduhnya setelah kedaluwarsa.
-
Moderasi konten: Semua prompt, gambar input, dan gambar output menjalani moderasi konten. Permintaan yang berisi konten terlarang mengembalikan kesalahan seperti “IPInfringementSuspect” atau “DataInspectionFailed”. Lihat Informasi kesalahan untuk detailnya.
Kode kesalahan
Jika panggilan model gagal dan mengembalikan pesan kesalahan, lihat 错误码 untuk penyelesaiannya.
FAQ
T: Saya sebelumnya menggunakan General Image Editing 2.1. Apakah saya perlu mengubah panggilan SDK saya untuk menggunakan wan2.5?
J: Anda perlu melakukan penyesuaian karena desain parameter berbeda antara kedua versi tersebut:
-
General Image Editing 2.1: Memerlukan parameter
promptdanfunction. -
General Image Editing 2.5: Hanya memerlukan
prompt. Gambarkan semua pengeditan dalam teks. Parameterfunctiontidak lagi didukung atau diperlukan.
T: Bagaimana cara melihat metrik penggunaan model?
J: Satu jam setelah panggilan model selesai, buka halaman Telemetri model (Singapura)Telemetri model (Beijing) untuk melihat metrik seperti jumlah panggilan dan tingkat keberhasilan. Untuk panduan langkah demi langkah, lihat Bagaimana cara melihat riwayat panggilan model?.



