Qwen-Image adalah model generasi gambar serbaguna yang mendukung berbagai gaya artistik dan unggul dalam complex text rendering. Model ini mendukung tata letak multi-baris, generasi teks tingkat paragraf, serta rendering detail halus.
Akses cepat: Panduan pengguna | Coba langsung (Singapura | Beijing) | Blog teknis (lebih banyak contoh) |
Contoh
Prompt | Gambar yang dihasilkan |
Poster bergaya healing bergambar tangan yang menampilkan tiga anak anjing bermain bola di atas rumput hijau subur, dihiasi elemen dekoratif seperti burung dan bintang. Judul utama “Come Play Ball!” muncul mencolok di bagian atas dengan font kartun biru tebal. Di bawahnya, subjudul “Come [Show Off Your Skills]!” muncul dengan font hijau. Gelembung ucapan menambah daya tarik lucu dengan teks: “Hehe, watch me amaze my little friends next!” Di bagian bawah, teks tambahan berbunyi: “We get to play ball with our friends again!” Palet warna berpusat pada hijau dan biru segar, dengan aksen merah muda dan kuning cerah untuk menonjolkan suasana ceria ala anak-anak. |
|
Ikhtisar model
Model | Deskripsi | Spesifikasi gambar output |
qwen-image-2.0-pro Kemampuan sama dengan qwen-image-2.0-pro-2026-03-03 | Seri Qwen Pro untuk generasi dan editing gambar. Menawarkan rendering teks lebih kuat, tekstur realistis, dan kepatuhan semantik. Untuk editing gambar, lihat Qwen-Image Editing. | Resolusi: Atur lebar dan tinggi secara bebas. Total piksel harus antara 512*512 hingga 2048*2048. Resolusi default adalah 2048*2048. Format: PNG Jumlah gambar: 1–6 |
qwen-image-2.0-pro-2026-03-03 | ||
qwen-image-2.0 Kemampuan sama dengan qwen-image-2.0-2026-03-03 | Seri Qwen accelerated untuk generasi dan editing gambar. Menyeimbangkan kualitas dan kecepatan respons. Untuk editing gambar, lihat Qwen-Image Editing. | |
qwen-image-2.0-2026-03-03 | ||
qwen-image-max Kemampuan sama dengan qwen-image-max-2025-12-30 | Seri Qwen Max untuk generasi gambar. Memberikan realisme dan naturalisme lebih tinggi, dengan lebih sedikit artefak hasil AI. | Resolusi: Lihat pengaturan parameter ukuran untuk resolusi dan rasio aspek yang didukung. Format: PNG Jumlah gambar: Tetap 1 |
qwen-image-max-2025-12-30 | ||
qwen-image-plus Kemampuan sama dengan qwen-image | Seri Qwen Plus untuk generasi gambar. Unggul dalam berbagai gaya artistik dan rendering teks. | |
qwen-image-plus-2026-01-09 | ||
qwen-image |
Hanya qwen-image-plus dan qwen-image yang mendukung panggilan asinkron.
Sebelum memanggil API, periksa daftar model yang didukung 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 Beijing dan Singapura memiliki Kunci API dan Titik akhir permintaan yang terpisah. Jangan gunakan secara bergantian. Panggilan lintas wilayah menyebabkan kegagalan otentikasi atau kesalahan layanan.
API Sinkron (direkomendasikan)
HTTP
Qwen-Image mendukung panggilan sinkron, mengembalikan hasil dalam satu permintaan.
Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Parameter permintaan | Text-to-image |
Header permintaan | |
Content-Type Tipe konten permintaan. Harus | |
Authorization Kredensial otentikasi menggunakan Kunci API Model Studio. Contoh: | |
Body permintaan | |
model Nama model. Contoh: | |
input Informasi input. | |
parameters Parameter pemrosesan gambar. |
Parameter respons | Tugas berhasilURL gambar hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan. Tugas gagalJika tugas gagal, respons menyertakan detail kesalahan di bidang kode dan pesan. LihatPesan kesalahan. |
output Informasi output tugas. | |
usage Statistik output. Hanya menghitung hasil yang berhasil. | |
request_id Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan troubleshooting masalah. | |
code Kode kesalahan. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detail. | |
message Pesan kesalahan detail. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detail. |
Panggilan SDK DashScope
SDK DashScope mendukung Python dan Java.
Nama parameter dalam SDK mirip dengan parameter HTTP, dan struktur parameternya mengikuti konvensi spesifik bahasa. Untuk parameter panggilan sinkron, lihat HTTP.
Python
Anda harus menginstal SDK Python DashScope versi terbaru. Jika tidak, kesalahan waktu proses dapat terjadi: Instal SDK.
Contoh permintaan
import json
import os
import dashscope
from dashscope import MultiModalConversation
# Gunakan URL ini untuk wilayah Singapura. Untuk wilayah Beijing, ganti dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"text": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."}
]
}
]
# Kunci API berbeda antara wilayah Beijing dan Singapura. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Jika Anda belum mengatur variabel lingkungan, ganti baris di bawah ini dengan: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-2.0-pro",
messages=messages,
result_format='message',
stream=False,
watermark=False,
prompt_extend=True,
negative_prompt="Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
size='2048*2048'
)
if response.status_code == 200:
print(json.dumps(response, ensure_ascii=False))
else:
print(f"Kode status HTTP: {response.status_code}")
print(f"Kode kesalahan: {response.code}")
print(f"Pesan kesalahan: {response.message}")
print("Lihat dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/error-code")
Contoh respons
URL gambar kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
"status_code": 200,
"request_id": "d2d1a8c0-325f-9b9d-8b90-xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"width": 2048,
"image_count": 1,
"height": 2048
}
}Java
Anda harus menginstal SDK Java DashScope versi terbaru. Jika tidak, kesalahan waktu proses dapat terjadi: Instal SDK.
Contoh permintaan
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class QwenImage {
static {
// Gunakan URL ini untuk wilayah Singapura. Untuk wilayah Beijing, ganti dengan: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Kunci API berbeda antara wilayah Beijing dan Singapura. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// Jika Anda belum mengatur variabel lingkungan, ganti baris di bawah ini dengan: static String apiKey="sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("text", "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.")
)).build();
Map<String, Object> parameters = new HashMap<>();
parameters.put("watermark", false);
parameters.put("prompt_extend", true);
parameters.put("negative_prompt", "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.");
parameters.put("size", "2048*2048");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-2.0-pro")
.messages(Collections.singletonList(userMessage))
.parameters(parameters)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
call();
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
Contoh respons
URL gambar kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
"requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
"usage": {
"image_count": 1,
"width": 2048,
"height": 2048
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
}
}API Asinkron
Hanya qwen-image-plus dan qwen-image yang mendukung panggilan asinkron.
HTTP
Qwen-Image juga mendukung panggilan asinkron. Alur kerja HTTP terdiri dari dua langkah:
Buat tugas untuk mendapatkan ID tugas: Kirim permintaan untuk membuat tugas. Respons mengembalikan ID tugas (task_id).
Poll hasil menggunakan ID tugas: Anda dapat menggunakan task_id untuk memeriksa status tugas hingga selesai dan mengembalikan URL gambar.
Langkah 1: Buat tugas untuk mendapatkan ID tugas
Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Beijing: POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
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 tutorial pemula, lihat Panggil API generasi gambar dan video menggunakan Postman atau cURL.
Parameter permintaan | Text-to-imageHanya |
Header permintaan | |
Content-Type Tipe konten permintaan. Harus | |
Authorization Kredensial otentikasi menggunakan Kunci API Model Studio. Contoh: | |
X-DashScope-Async Mengaktifkan pemrosesan asinkron. Harus Penting Mengembalikan kesalahan "current user api does not support synchronous calls" jika tidak disertakan. | |
Body permintaan | |
model Nama model. Hanya Contoh: | |
input Informasi input. | |
parameters Parameter pemrosesan gambar. |
Parameter respons | Respons berhasilSimpan Respons kesalahanPembuatan tugas gagal. Lihat kode kesalahan untuk mengatasi masalah. |
output Informasi output tugas. | |
request_id Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan troubleshooting masalah. | |
code Kode kesalahan. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detail. | |
message Pesan kesalahan detail. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detail. |
Langkah 2: Tanyakan hasil menggunakan ID Tugas
Singapura: GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
Beijing: GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
Saran polling: Generasi gambar membutuhkan waktu. Gunakan mekanisme polling dengan interval permintaan yang wajar, misalnya 10 detik, untuk mengambil hasilnya.
Transisi status tugas: PENDING → RUNNING → SUCCEEDED atau FAILED.
URL hasil: Setelah tugas berhasil, URL gambar dikembalikan. URL berlaku selama 24 jam. Setelah Anda mendapatkan URL, segera unduh dan simpan gambar ke layanan penyimpanan permanen, seperti Object Storage Service (OSS).
Parameter permintaan | Poll hasil tugasGanti |
Header permintaan | |
Authorization Kredensial otentikasi menggunakan Kunci API Model Studio. Contoh: | |
Parameter path URL | |
task_id ID tugas yang akan ditanyakan. |
Parameter respons | Tugas berhasilData tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan. Tugas gagalSaat tugas gagal, |
output Informasi output tugas. | |
usage Statistik output. Hanya menghitung hasil yang berhasil. | |
request_id Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan troubleshooting masalah. |
SDK DashScope
SDK DashScope mendukung Python dan Java.
Nama parameter SDK mirip dengan parameter HTTP yang sesuai. Struktur parameter mengikuti konvensi spesifik bahasa. Untuk detail parameter panggilan asinkron, lihat HTTP.
Karena model gambar memerlukan waktu pemrosesan lebih lama, layanan dasar menggunakan eksekusi asinkron. SDK menyediakan dua mode untuk menangani ini:
Panggilan sinkron (mode blocking): SDK menunggu tugas selesai dan mengembalikan hasil akhir. Perilaku ini sama dengan panggilan sinkron standar.
Panggilan asinkron (mode non-blocking): Panggilan langsung mengembalikan ID tugas. Anda harus melakukan polling status tugas dan hasil akhir menggunakan ID tersebut.
Python SDK
Anda harus menginstal SDK Python DashScope versi terbaru. Jika tidak, kesalahan waktu proses dapat terjadi: Instal SDK.
Sinkron
Contoh permintaan
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# Gunakan URL ini untuk wilayah Singapura. Untuk wilayah Beijing, ganti dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."
# Kunci API berbeda antara wilayah Beijing dan Singapura. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Jika Anda belum mengatur variabel lingkungan, ganti baris di bawah ini dengan: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
print('----Panggilan sinkron, harap tunggu sebentar----')
rsp = ImageSynthesis.call(api_key=api_key,
model="qwen-image-plus", # Hanya qwen-image-plus dan qwen-image yang mendukung panggilan asinkron
prompt=prompt,
negative_prompt=" ",
n=1,
size='1664*928',
prompt_extend=True,
watermark=False)
print(f'respons: {rsp}')
if rsp.status_code == HTTPStatus.OK:
# Simpan gambar di 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(f'Panggilan sinkron gagal, status_code: {rsp.status_code}, kode: {rsp.code}, pesan: {rsp.message}')
Contoh respons
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
"status_code": 200,
"request_id": "a47b1a65-7041-4565-9068-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "91093132-475e-43cf-b94e-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxxxx",
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition."
}
],
"submit_time": "2025-09-09 13:39:20.659",
"scheduled_time": "2025-09-09 13:39:20.717",
"end_time": "2025-09-09 13:39:45.233"
},
"usage": {
"image_count": 1
}
}Asinkron
Contoh permintaan
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
import time
# Gunakan URL ini untuk wilayah Singapura. Untuk wilayah Beijing, ganti dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere."
# Kunci API berbeda antara wilayah Beijing dan Singapura. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Jika Anda belum mengatur variabel lingkungan, ganti baris di bawah ini dengan: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
def async_call():
print('----Membuat Tugas----')
task_info = create_async_task()
print('----Melakukan Polling Status Tugas----')
poll_task_status(task_info)
# Buat tugas asinkron
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="qwen-image-plus", # Hanya qwen-image-plus dan qwen-image yang mendukung panggilan asinkron
prompt=prompt,
negative_prompt=" ",
n=1,
size='1664*928',
prompt_extend=True,
watermark=False)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print(f'Gagal membuat tugas, status_code: {rsp.status_code}, kode: {rsp.code}, pesan: {rsp.message}')
return rsp
# Poll status tugas asinkron, kueri setiap 5 detik, polling maksimal 1 menit
def poll_task_status(task):
start_time = time.time()
timeout = 60 # Batas waktu 1 menit
while True:
# Periksa apakah batas waktu habis
if time.time() - start_time > timeout:
print('Batas waktu polling (1 menit), tugas belum selesai')
return
# Dapatkan status tugas
status_rsp = ImageSynthesis.fetch(task)
print(f'Hasil kueri status tugas: {status_rsp}')
if status_rsp.status_code != HTTPStatus.OK:
print(f'Gagal mendapatkan status tugas, status_code: {status_rsp.status_code}, kode: {status_rsp.code}, pesan: {status_rsp.message}')
return
task_status = status_rsp.output.task_status
print(f'Status tugas saat ini: {task_status}')
if task_status == 'SUCCEEDED':
print('Tugas selesai, mengunduh gambar...')
for result in status_rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open(f'./{file_name}', 'wb+') as f:
f.write(requests.get(result.url).content)
print(f'Gambar disimpan sebagai: {file_name}')
break
elif task_status == 'FAILED':
print(f'Eksekusi tugas gagal, status: {task_status}, kode: {status_rsp.code}, pesan: {status_rsp.message}')
break
elif task_status == 'PENDING' or task_status == 'RUNNING':
print('Tugas sedang berjalan, lanjutkan kueri setelah 5 detik...')
time.sleep(5)
else:
print(f'Status tugas tidak dikenal: {task_status}, lanjutkan kueri setelah 5 detik...')
time.sleep(5)
# Batalkan tugas asinkron, hanya tugas dengan status PENDING yang dapat dibatalkan
def cancel_task(task):
rsp = ImageSynthesis.cancel(task)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print(f'Gagal membatalkan tugas, status_code: {rsp.status_code}, kode: {rsp.code}, pesan: {rsp.message}')
if __name__ == '__main__':
async_call()
Contoh respons
1. Respons untuk pembuatan tugas
{
"status_code": 200,
"request_id": "31b04171-011c-96bd-ac00-xxxxxx",
"code": "",
"message": "",
"output": {
"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
"task_status": "PENDING",
"results": []
},
"usage": null
}2. Respons untuk polling hasil tugas
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
"status_code": 200,
"request_id": "a47b1a65-7041-4565-9068-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "91093132-475e-43cf-b94e-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxxxx",
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition."
}
],
"submit_time": "2025-09-09 13:39:20.659",
"scheduled_time": "2025-09-09 13:39:20.717",
"end_time": "2025-09-09 13:39:45.233"
},
"usage": {
"image_count": 1
}
}SDK Java
Anda harus menginstal SDK Java DashScope versi terbaru. Jika tidak, kesalahan waktu proses dapat terjadi: Instal SDK.
Sinkron
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.HashMap;
import java.util.Map;
public class Text2Image {
static {
// Gunakan URL ini untuk wilayah Singapura. Untuk wilayah Beijing, ganti dengan: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Kunci API berbeda antara wilayah Beijing dan Singapura. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// Jika Anda belum mengatur variabel lingkungan, ganti baris di bawah ini dengan: static String apiKey = "sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException {
String prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.";
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("negative_prompt", " ");
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
// Hanya qwen-image-plus dan qwen-image yang mendukung panggilan asinkron
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1664*928")
.parameters(parameters)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
System.out.println("---Panggilan sinkron, harap tunggu sebentar----");
result = imageSynthesis.call(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args){
try{
basicCall();
}catch(ApiException|NoApiKeyException e){
System.out.println(e.getMessage());
}
}
}
Contoh respons
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
"request_id": "9f3044ba-528f-4606-8830-xxxxxx",
"output": {
"task_id": "fecf4c7f-3508-45f4-8454-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition.",
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
}
]
},
"usage": {
"image_count": 1
}
}Asinkron
Contoh permintaan
// 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.util.HashMap;
import java.util.Map;
public class Text2Image {
static {
// Gunakan URL ini untuk wilayah Singapura. Untuk wilayah Beijing, ganti dengan: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Kunci API berbeda antara wilayah Beijing dan Singapura. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// Jika Anda belum mengatur variabel lingkungan, ganti baris di bawah ini dengan: static String apiKey = "sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public void asyncCall() {
System.out.println("---Membuat tugas----");
String taskId = this.createAsyncTask();
System.out.println("--Menunggu hingga tugas selesai dan mengembalikan url gambar----");
this.waitAsyncTask(taskId);
}
public String createAsyncTask() {
String prompt = "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.";
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("negative_prompt", " ");
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
// Hanya qwen-image-plus dan qwen-image yang mendukung panggilan asinkron
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1664*928")
.parameters(parameters)
.build();
try {
ImageSynthesisResult result = new ImageSynthesis().asyncCall(param);
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
System.out.println("task_id=" + taskId);
return taskId;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
long startTime = System.currentTimeMillis();
int timeout = 60 * 1000; // Batas waktu 1 menit
int interval = 5 * 1000; // Interval polling 5 detik
while (true) {
if (System.currentTimeMillis() - startTime > timeout) {
System.out.println("Batas waktu polling (1 menit), tugas belum selesai");
return;
}
try {
ImageSynthesisResult result = imageSynthesis.fetch(taskId, apiKey);
System.out.println("Hasil kueri status tugas: " + JsonUtils.toJson(result));
if (result.getOutput() == null) {
System.out.println("Gagal mendapatkan status tugas, output kosong");
return;
}
String taskStatus = result.getOutput().getTaskStatus();
System.out.println("Status tugas saat ini: " + taskStatus);
switch (taskStatus) {
case "SUCCEEDED":
System.out.println("Tugas selesai");
System.out.println(JsonUtils.toJson(result));
return;
case "FAILED":
System.out.println("Eksekusi tugas gagal, status: " + taskStatus);
return;
case "PENDING":
case "RUNNING":
System.out.println("Tugas sedang berjalan, kueri lagi dalam 5 detik...");
Thread.sleep(interval);
break;
default:
System.out.println("Status tugas tidak dikenal: " + taskStatus + ", kueri lagi dalam 5 detik...");
Thread.sleep(interval);
break;
}
} catch (ApiException | NoApiKeyException e) {
System.err.println("Pengecualian panggilan API: " + e.getMessage());
return;
} catch (InterruptedException e) {
System.err.println("Pengecualian gangguan thread: " + e.getMessage());
Thread.currentThread().interrupt();
return;
}
}
}
public static void main(String[] args){
Text2Image text2Image = new Text2Image();
text2Image.asyncCall();
}
}Contoh respons
1. Respons untuk pembuatan tugas
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}2. Respons untuk polling hasil tugas
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
"request_id": "9f3044ba-528f-4606-8830-xxxxxx",
"output": {
"task_id": "fecf4c7f-3508-45f4-8454-xxxxxx",
"task_status": "SUCCEEDED",
"results": [
{
"orig_prompt": "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.",
"actual_prompt": "Childhood-inspired hand-drawn poster design: Three playful puppies joyfully interact with a colorful ball on a vibrant patch of lush green grass. Delicate decorative elements including fluttering birds and twinkling stars are scattered throughout. At the top center, the bold, blue cartoon-style title “Come Play Ball!” stands out prominently. Directly beneath, the subtitle “Come [Show Off Your Skills]!” is rendered in cheerful green lettering. A whimsical speech bubble near one of the puppies contains the playful text: “Hehe, watch me amaze my little friends next!” At the bottom edge, smaller supplementary text reads: “We get to play ball with our friends again!” The color palette is centered on fresh greens and sky blues, accented with pops of bright pink and sunny yellow, enhancing the cheerful, childlike atmosphere. Style evokes nostalgic, hand-inked illustrations with soft textures, gentle linework, and a whimsical, storybook-like composition.",
"url": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
}
]
},
"usage": {
"image_count": 1
}
}Penagihan dan pembatasan laju
Untuk kuota gratis dan harga, lihat Harga model.
Untuk batas laju, lihat Qwen-Image.
Detail penagihan: Anda ditagih per gambar yang berhasil dihasilkan. Panggilan gagal atau kesalahan pemrosesan tidak dikenai biaya atau mengurangi kuota gratis pengguna baru Anda.
Kode kesalahan
Jika panggilan model gagal dan mengembalikan pesan kesalahan, lihat Pesan kesalahan untuk penyelesaian.
FAQ
T: Haruskah saya mengaktifkan atau menonaktifkan parameter prompt_extend?
J: Aktifkan opsi ini (default) jika Anda menginginkan konten gambar lebih beragam dan agar model menambahkan detail. Nonaktifkan jika Anda memerlukan kontrol lebih ketat atas detail gambar, dan optimalkan prompt Anda menggunakan Panduan Prompt Text-to-Image.
T: Apa perbedaan antara qwen-image, qwen-image-plus, qwen-image-max, qwen-image-2.0, dan qwen-image-edit?
A:
Model gabungan generasi dan editing gambar: Mendukung text-to-image dan editing gambar.
qwen-image-2.0-prodanqwen-image-2.0-pro-2026-03-03: Kemampuan sama. Seri Pro memberikan rendering teks lebih profesional, tekstur realistis lebih halus, adegan realistis detail, dan kepatuhan semantik lebih kuat. Hanya mendukung panggilan sinkron.qwen-image-2.0danqwen-image-2.0-2026-03-03: Kemampuan sama. Versi accelerated menyeimbangkan performa dan kualitas model. Hanya mendukung panggilan sinkron.
Model text-to-image: Menghasilkan gambar dari deskripsi teks.
qwen-image-maxdanqwen-image-max-2025-12-30: Kemampuan sama. Dibandingkan denganqwen-image-plus, memberikan realisme dan naturalisme lebih baik, dengan hasil lebih baik untuk tekstur karakter, detail, dan rendering teks.qwen-imagedanqwen-image-plus: Kemampuan sama, tetapiqwen-image-pluslebih hemat biaya.qwen-image-plus-2026-01-09: Versi snapshot baru Qwen-Image. Ini adalah versi distilasi dan dipercepat dariqwen-image-maxyang mendukung generasi cepat gambar berkualitas tinggi.
Model editing gambar:
qwen-image-edit: Melakukan transformasi image-to-image, inpainting, dan operasi lain berdasarkan gambar input dan instruksi teks. Untuk informasi lebih lanjut, lihat Qwen - image editing.
T: Bagaimana cara mendapatkan daftar putih nama domain untuk penyimpanan gambar?
J: Gambar yang dihasilkan model disimpan di OSS. API mengembalikan URL publik sementara. Untuk mengonfigurasi daftar putih firewall untuk URL unduhan ini, perhatikan hal berikut: Penyimpanan dasar dapat berubah secara dinamis. Topik ini tidak menyediakan daftar putih nama domain OSS tetap untuk mencegah masalah akses akibat informasi usang. Jika Anda memiliki persyaratan kontrol keamanan, hubungi manajer akun Anda untuk mendapatkan daftar nama domain OSS terbaru.
