Qwen-Image adalah model generasi citra tujuan umum yang mendukung berbagai gaya artistik dan unggul dalam rendering teks kompleks. Model ini mampu menghasilkan teks multi-baris hingga tingkat paragraf serta merender detail halus, sehingga memungkinkan desain kompleks yang menggabungkan teks dan gambar.
Tautan cepat: Panduan pengguna | Coba online | Blog teknis (lebih banyak contoh) |
Etalase
Prompt masukan | Gambar keluaran |
Poster bergambar tangan bergaya penyembuhan yang menampilkan tiga anak anjing bermain bola di atas rumput hijau yang subur, dihiasi elemen dekoratif seperti burung dan bintang. Judul utama “Come Play Ball!” ditampilkan mencolok di bagian atas dengan font kartun biru tebal. Di bawahnya, subjudul “Come [Show Off Your Skills]!” muncul dengan font hijau. Balon ucapan menambah daya tarik bermain 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 warna merah muda dan kuning cerah untuk menonjolkan suasana ceria dan kekanak-kanakan. |
|
Prasyarat
Sebelum melakukan panggilan, buat kunci API untuk wilayah Anda. Kemudian, ekspor kunci API sebagai variabel lingkungan.
Wilayah Beijing dan Singapura memiliki kunci API dan titik akhir permintaan yang terpisah. Jangan menggunakannya secara bergantian karena panggilan lintas wilayah dapat menyebabkan kegagalan otentikasi atau kesalahan layanan.
API Sinkron (direkomendasikan)
Panggilan HTTP
Qwen-Image mendukung API sinkron yang memungkinkan Anda memperoleh hasil dalam satu permintaan saja. Karena proses pemanggilannya sederhana, API ini direkomendasikan untuk sebagian besar skenario.
Wilayah Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Wilayah Tiongkok (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Parameter permintaan | Teks-ke-gambar |
Header permintaan | |
Content-Type Tipe konten permintaan. Atur parameter ini ke | |
Authorization Kredensial otentikasi identitas untuk permintaan. API ini menggunakan Kunci API Model Studio untuk otentikasi identitas. Contoh: Bearer sk-xxxx. | |
Isi permintaan | |
model Nama model. Atur parameter ini ke | |
input Masukkan informasi dasar. | |
parameters Parameter pemrosesan gambar. |
Parameter respons | Tugas berhasilData tugas, seperti status tugas dan URL gambar, hanya disimpan selama 24 jam dan secara otomatis dihapus setelah periode ini. Anda harus segera menyimpan gambar yang dihasilkan. Tugas tidak normalJika tugas gagal, respons menyertakan informasi kegagalan. Kolom `code` dan `message` menunjukkan penyebab kesalahan. Untuk informasi lebih lanjut tentang cara menyelesaikan masalah, lihat Pesan kesalahan. |
output Informasi keluaran tugas. | |
usage Statistik penggunaan untuk keluaran. Hanya hasil yang berhasil yang dihitung. | |
request_id ID permintaan unik. Anda dapat menggunakan ID ini untuk melacak dan memecahkan masalah. | |
code Kode kesalahan untuk permintaan yang gagal. Parameter ini tidak dikembalikan jika permintaan berhasil. Untuk informasi lebih lanjut, lihat Pesan kesalahan. | |
message Informasi detail tentang permintaan yang gagal. Parameter ini tidak dikembalikan jika permintaan berhasil. Untuk informasi lebih lanjut, lihat Pesan kesalahan. |
SDK DashScope
SDK DashScope saat ini mendukung Python dan Java.
Nama parameter dalam SDK sebagian besar konsisten dengan API HTTP. Struktur parameter dienkapsulasi berdasarkan fitur bahasa. Untuk deskripsi parameter panggilan sinkron, lihat Panggilan HTTP.
Python
Pastikan Anda telah menginstal versi terbaru SDK Python DashScope. Jika tidak, kesalahan waktu proses dapat terjadi. Untuk informasi lebih lanjut, lihat Instal SDK.
Contoh permintaan
import json
import os
import dashscope
from dashscope import MultiModalConversation
# URL berikut ini untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Tiongkok (Beijing), ganti URL 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 untuk wilayah Singapura dan Tiongkok (Beijing) berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-plus",
messages=messages,
result_format='message',
stream=False,
watermark=False,
prompt_extend=True,
negative_prompt='',
size='1328*1328'
)
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("Untuk informasi lebih lanjut, lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code")Contoh respons
URL gambar berlaku selama 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"
}
]
}
}
],
"task_metric": {
"TOTAL": 1,
"FAILED": 0,
"SUCCEEDED": 1
}
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"width": 1328,
"image_count": 1,
"height": 1328
}
}Java
Pastikan Anda telah menginstal versi terbaru SDK Java DashScope. Jika tidak, kesalahan waktu proses dapat terjadi. Untuk informasi lebih lanjut, lihat 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 {
// Berikut ini adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Tiongkok (Beijing), ganti base_url dengan: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Kunci API untuk wilayah Singapura dan Tiongkok (Beijing) berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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", "");
parameters.put("size", "1328*1328");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-plus")
.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 berlaku selama 24 jam. Unduh gambar segera.
{
"requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
"usage": {
"image_count": 1,
"width": 1328,
"height": 1328
},
"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 (proses dua langkah)
Panggilan HTTP
Qwen-Image juga mendukung API asinkron. Alur panggilan HTTP terdiri dari dua langkah:
Buat tugas untuk mendapatkan ID tugas: Kirim permintaan untuk membuat tugas. Respons mengembalikan ID tugas (task_id).
Kueri hasil menggunakan ID tugas: Gunakan `task_id` untuk memeriksa status tugas hingga tugas selesai dan Anda mendapatkan URL gambar.
Langkah 1: Buat tugas untuk mendapatkan ID tugas
Wilayah Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Wilayah Tiongkok (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Setelah tugas dibuat, gunakan
task_idyang dikembalikan untuk mengkueri hasil. task_id berlaku selama 24 jam. Jangan membuat tugas duplikat. Gunakan polling untuk mengambil hasil.
Parameter permintaan | Teks-ke-gambar |
Header permintaan | |
Content-Type Tipe konten permintaan. Atur parameter ini ke | |
Authorization Kredensial otentikasi identitas untuk permintaan. API ini menggunakan Kunci API Model Studio untuk otentikasi identitas. Contoh: Bearer sk-xxxx. | |
X-DashScope-Async Parameter konfigurasi pemrosesan asinkron. Permintaan HTTP hanya mendukung pemrosesan asinkron. Anda harus mengatur parameter ini ke Penting Jika header permintaan ini tidak ada, pesan kesalahan "current user api does not support synchronous calls" dikembalikan. | |
Isi permintaan | |
model Nama model. Atur parameter ini ke | |
input Informasi masukan dasar, seperti prompt. | |
parameters Parameter pemrosesan gambar. |
Parameter respons | Respons berhasilSimpan task_id untuk mengkueri status tugas dan hasil. Respons kesalahanPembuatan tugas gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan untuk menyelesaikan masalah. |
output Informasi keluaran tugas. | |
request_id ID permintaan unik. Anda dapat menggunakan ID ini untuk melacak dan memecahkan masalah. | |
code Kode kesalahan untuk permintaan yang gagal. Parameter ini tidak dikembalikan jika permintaan berhasil. Untuk informasi lebih lanjut, lihat Pesan kesalahan. | |
message Informasi detail tentang permintaan yang gagal. Parameter ini tidak dikembalikan jika permintaan berhasil. Untuk informasi lebih lanjut, lihat Pesan kesalahan. |
Langkah 2: Kueri hasil menggunakan ID tugas
Wilayah Singapura: GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
Wilayah Beijing: GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
Rekomendasi polling: Model membutuhkan waktu sekitar 15 detik untuk berjalan. Kami menyarankan Anda menggunakan mekanisme polling dengan interval kueri yang wajar, misalnya 3 detik, untuk mengambil hasil. Waktu aktual tergantung pada jumlah tugas dalam antrian dan kondisi jaringan. Harap tunggu hasilnya.
Alur status tugas: PENDING -> RUNNING -> SUCCEEDED / FAILED.
Tautan hasil: Setelah tugas berhasil, tautan gambar dikembalikan. Tautan berlaku selama 24 jam. Anda harus segera mengunduh dan memindahkan gambar ke ruang penyimpanan, seperti Alibaba Cloud OSS.
Parameter permintaan | Kueri hasil tugasGanti Kunci API untuk wilayah Singapura dan Beijing berbeda. Dapatkan kunci API. Kode berikut ini menyediakan base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan https://dashscope.aliyuncs.com/api/v1/tasks/{task_id} |
Header permintaan | |
Authorization Kredensial otentikasi identitas untuk permintaan. API ini menggunakan Kunci API Model Studio untuk otentikasi identitas. Contoh: Bearer sk-xxxx. | |
Parameter path URL | |
task_id ID tugas. |
Parameter respons | Tugas berhasilData tugas, seperti status tugas dan URL gambar, hanya disimpan selama 24 jam dan secara otomatis dihapus setelah periode ini. Anda harus segera menyimpan gambar yang dihasilkan. Tugas gagalJika tugas gagal, task_status diatur ke FAILED, dan kode kesalahan serta pesan disediakan. Untuk informasi lebih lanjut, lihat Pesan kesalahan untuk menyelesaikan masalah. |
output Informasi keluaran tugas. | |
usage Statistik penggunaan untuk keluaran. Hanya hasil yang berhasil yang dihitung. | |
request_id ID permintaan unik. Anda dapat menggunakan ID ini untuk melacak dan memecahkan masalah. |
SDK DashScope
SDK DashScope saat ini mendukung Python dan Java.
Nama parameter dalam SDK sebagian besar konsisten dengan API HTTP. Struktur parameter tergantung pada enkapsulasi SDK untuk setiap bahasa. Untuk deskripsi parameter panggilan asinkron, lihat Panggilan HTTP.
Karena model gambar memerlukan waktu pemrosesan yang lama, layanan dasar bersifat asinkron. SDK membangun di atas ini dengan menyediakan dua mode pemanggilan berikut:
Panggilan sinkron (mode pemblokiran): SDK secara otomatis menunggu tugas selesai dan kemudian langsung mengembalikan hasil akhir. Pengalaman pemanggilan konsisten dengan panggilan sinkron biasa.
Panggilan asinkron (mode non-pemblokiran): Pemanggilan segera mengembalikan ID tugas. Anda harus menggunakan ID ini untuk mengkueri status tugas dan hasil akhir.
SDK Python
Pastikan Anda telah menginstal versi terbaru SDK Python DashScope. Jika tidak, kesalahan waktu proses dapat terjadi. Untuk informasi lebih lanjut, lihat Instal SDK.
Panggilan 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
# URL berikut ini untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Tiongkok (Beijing), ganti URL 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 untuk wilayah Singapura dan Tiongkok (Beijing) berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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",
prompt=prompt,
n=1,
size='1328*1328',
prompt_extend=True,
watermark=False)
print(f'respons: {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(f'panggilan_sinkron Gagal, status_code: {rsp.status_code}, kode: {rsp.code}, pesan: {rsp.message}')
Contoh respons
URL berlaku selama 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
}
}Panggilan 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
# URL berikut ini untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Tiongkok (Beijing), ganti URL dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.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 untuk wilayah Singapura dan Tiongkok (Beijing) berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
def async_call():
print('----Membuat Tugas----')
task_info = create_async_task()
print('----Memeriksa Status Tugas----')
poll_task_status(task_info)
# Membuat tugas asinkron.
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="qwen-image-plus",
prompt=prompt,
n=1,
size='1328*1328',
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
# Memeriksa status tugas asinkron, kueri setiap 5 detik, maksimal polling selama 1 menit.
def poll_task_status(task):
start_time = time.time()
timeout = 60 # batas waktu 1 menit
while True:
# Periksa batas waktu.
if time.time() - start_time > timeout:
print('Batas waktu polling terlampaui (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, mengkueri lagi dalam 5 detik...')
time.sleep(5)
else:
print(f'Status tugas tidak dikenal: {task_status}, mengkueri lagi dalam 5 detik...')
time.sleep(5)
# Membatalkan tugas asinkron. Anda hanya dapat membatalkan tugas yang berada dalam status PENDING.
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. Contoh respons untuk membuat 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. Contoh respons untuk mengkueri hasil tugas
URL berlaku selama 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
Pastikan Anda telah menginstal versi terbaru SDK Java DashScope. Jika tidak, kesalahan waktu proses dapat terjadi. Untuk informasi lebih lanjut, lihat Instal SDK.
Panggilan sinkron
Contoh permintaan
// Hak Cipta (c) Alibaba, Inc. dan afiliasinya.
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 {
// URL berikut ini untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Tiongkok (Beijing), ganti URL dengan: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Kunci API untuk wilayah Singapura dan Tiongkok (Beijing) berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1328*1328")
.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 berlaku selama 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
}
}Panggilan asinkron
Contoh permintaan
// Hak Cipta (c) Alibaba, Inc. dan afiliasinya.
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 {
// URL berikut ini untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Tiongkok (Beijing), ganti URL dengan: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// Kunci API untuk wilayah Singapura dan Tiongkok (Beijing) berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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 tugas selesai dan mengembalikan url gambar----");
this.waitAsyncTask(taskId);
}
/**
* Membuat tugas asinkron.
* @return 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);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("qwen-image-plus")
.prompt(prompt)
.n(1)
.size("1328*1328")
.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());
}
}
/**
* Menunggu tugas asinkron selesai.
* @param taskId ID tugas.
* */
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 terlampaui (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, mengkueri lagi dalam 5 detik...");
Thread.sleep(interval);
break;
default:
System.out.println("Status tugas tidak dikenal: " + taskStatus + ", mengkueri 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. Contoh respons untuk membuat tugas
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}2. Contoh respons untuk mengkueri hasil tugas
URL berlaku selama 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 batas laju
Model qwen-image-plus dan qwen-image memiliki kemampuan yang sama, tetapi qwen-image-plus lebih hemat biaya dan direkomendasikan.
Wilayah Singapura
Model | Harga satuan | Batas laju (dibagi oleh Akun Alibaba Cloud dan Pengguna RAM) | Kuota gratis | |
Batas RPS pengiriman tugas | Jumlah tugas konkuren | |||
qwen-image-plus | $0,03/gambar | 2 | 2 | Kuota gratis: 100 gambar untuk setiap model Periode berlaku: Dalam 90 hari setelah Anda mengaktifkan Alibaba Cloud Model Studio. |
qwen-image | $0,035/gambar | 2 | 2 | |
Wilayah Tiongkok (Beijing)
Model | Harga satuan | Batas laju (dibagi oleh Akun Alibaba Cloud dan Pengguna RAM) | Kuota gratis | |
Batas RPS pengiriman tugas | Jumlah tugas konkuren | |||
qwen-image-plus | $0,028671/gambar | 2 | 2 | Tidak ada kuota gratis |
qwen-image | $0,035/gambar | 2 | 2 | |
Aturan penagihan
Item yang ditagih: Anda ditagih berdasarkan jumlah gambar yang berhasil dihasilkan dengan metode penagihan bayar sesuai pemakaian.
Rumus penagihan: Biaya = Harga satuan × Jumlah gambar.
Urutan konsumsi: Kuota gratis dikonsumsi terlebih dahulu. Setelah kuota gratis Anda habis, metode penagihan bayar sesuai pemakaian digunakan secara default.
Anda dapat mengaktifkan opsi "Hanya kuota gratis" untuk mencegah biaya setelah kuota gratis Anda habis. Untuk informasi lebih lanjut, lihat Kuota gratis untuk pengguna baru.
Tidak dikenai biaya untuk kegagalan: Panggilan model yang gagal atau kesalahan pemrosesan tidak dikenai biaya atau mengurangi kuota gratis.
Kuota gratis
Untuk informasi lebih lanjut tentang cara mengklaim, mengkueri, dan menggunakan kuota gratis, lihat Kuota gratis untuk pengguna baru.
Kueri penggunaan
Sekitar satu jam setelah panggilan model selesai, Anda dapat membuka halaman Pengamatan Model (Singapura) untuk melihat metrik seperti penggunaan, jumlah panggilan, dan tingkat keberhasilan.
Jika Anda menggunakan model di wilayah Tiongkok (Beijing), buka halaman Pengamatan Model untuk wilayah Tiongkok (Beijing).
Pembatasan laju
Untuk aturan pembatasan laju dan FAQ, lihat Batas laju.
Konfigurasi akses gambar
Gambar yang dihasilkan disimpan di Alibaba Cloud OSS. Setiap gambar diberikan tautan OSS, seperti https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png. Tautan OSS memungkinkan akses publik, dan Anda dapat menggunakannya untuk melihat atau mengunduh gambar. Tautan hanya berlaku selama 24 jam.
Jika bisnis Anda memiliki persyaratan keamanan tinggi dan tidak dapat mengakses tautan Alibaba Cloud OSS, Anda harus mengonfigurasi daftar putih untuk akses publik. Tambahkan nama domain berikut ke daftar putih Anda untuk mengakses tautan gambar.
# Daftar nama domain OSS
dashscope-result-bj.oss-cn-beijing.aliyuncs.com
dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com
dashscope-result-sh.oss-cn-shanghai.aliyuncs.com
dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com
dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com
dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com
dashscope-result-hy.oss-cn-heyuan.aliyuncs.com
dashscope-result-cd.oss-cn-chengdu.aliyuncs.com
dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com
dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.comKode kesalahan
Jika pemanggilan gagal, lihat Pesan kesalahan untuk pemecahan masalah.
FAQ
T: Haruskah saya mengaktifkan atau menonaktifkan parameter prompt_extend?
J: Anda harus tetap mengaktifkannya (default) jika prompt masukan Anda sederhana atau Anda ingin model lebih kreatif. Anda harus secara eksplisit mengaturnya ke false jika prompt Anda sudah detail dan profesional, atau jika Anda memiliki persyaratan ketat untuk latensi respons API.
T: Apa perbedaan antara model qwen-image, qwen-image-plus, dan qwen-image-edit?
J:
Model teks-ke-gambar:
qwen-imagedanqwen-image-plus
Model ini menghasilkan gambar dari deskripsi teks. Kedua model memiliki kemampuan yang sama, tetapiqwen-image-pluslebih hemat biaya dan direkomendasikan.Model pengeditan gambar:
qwen-image-edit
Model ini melakukan operasi seperti generasi gambar-ke-gambar dan modifikasi lokal berdasarkan gambar masukan dan instruksi teks. Untuk informasi lebih lanjut, lihat Qwen - pengeditan gambar.
