全部产品
Search
文档中心

Alibaba Cloud Model Studio:Qwen - referensi API teks-ke-gambar

更新时间:Jan 13, 2026

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 citra.

Tautan cepat: Panduan pengguna | Coba secara online (Singapura | Beijing) | Blog teknis (lebih banyak contoh)

Unjuk Kinerja

Masukkan prompt

Citra keluaran

Poster bergambar tangan bergaya healing yang menampilkan tiga anak anjing bermain bola di atas rumput hijau 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. Sebuah 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 segar dan biru, dengan aksen merah muda dan kuning cerah untuk menonjolkan suasana ceria ala anak-anak.

image

Ikhtisar model

Nama model

Deskripsi model

Spesifikasi citra output

qwen-image-max Direkomendasikan

Saat ini memiliki kemampuan yang sama dengan qwen-image-max-2025-12-30.

Qwen-Image-Max meningkatkan seri Plus dengan meningkatkan realisme dan kealamian citra. Model ini secara efektif mengurangi artefak hasil AI dan unggul dalam rendering tekstur karakter, detail halus, dan teks.

Resolusi citra: Untuk resolusi yang tersedia beserta rasio aspeknya, lihat pengaturan parameter ukuran.

Format citra: PNG

Jumlah citra: Tetap 1

qwen-image-max-2025-12-30 Direkomendasikan

qwen-image-plus Direkomendasikan

Saat ini memiliki kemampuan yang sama dengan qwen-image.

Mendukung berbagai gaya artistik dan unggul dalam rendering teks kompleks dalam citra, memungkinkan desain tata letak campuran teks-dan-citra.

qwen-image-plus-2026-01-09 Direkomendasikan

qwen-image

Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API asinkron.
Catatan

Sebelum melakukan panggilan, periksa Daftar model untuk memastikan ketersediaan model di wilayah Anda.

Prasyarat

Sebelum melakukan panggilan, dapatkan Kunci API dan atur Kunci API sebagai variabel lingkungan. Untuk melakukan panggilan menggunakan SDK, instal SDK DashScope.

Penting

Wilayah Beijing dan Singapura memiliki Kunci API dan Titik akhir permintaan yang berbeda. 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 mengambil hasil dengan satu permintaan. Karena proses pemanggilannya sederhana, API ini direkomendasikan untuk sebagian besar skenario.

Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Tiongkok (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Parameter permintaan

Teks-ke-gambar

curl --location 'https://dashscope-max.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "model": "qwen-image-max",
    "input": {
      "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."
            }
          ]
        }
      ]
    },
    "parameters": {
      "negative_prompt": "low resolution, low quality, deformed limbs, deformed fingers, oversaturated, waxy, no facial details, overly smooth, AI-like, chaotic composition, blurry text, distorted text.",
      "prompt_extend": true,
      "watermark": false,
      "size": "1664*928"
    }
}'
Header permintaan

Content-Type string (Wajib)

Tipe konten permintaan. Anda harus mengatur parameter ini ke application/json.

Authorization string (Wajib)

Kredensial otentikasi. API ini menggunakan Kunci API Model Studio untuk otentikasi. Contoh: `Bearer sk-xxxx`.

Body permintaan

model string (Wajib)

Nama model. Contoh: qwen-image-max.

input object (Wajib)

Informasi input dasar untuk model.

Properti

messages array (Wajib)

Array yang berisi konten permintaan. Saat ini, hanya percakapan satu giliran yang didukung. Array harus berisi tepat satu elemen.

Properti

role string (Wajib)

Peran pesan. Parameter ini harus diatur ke user.

content array (Wajib)

Array yang berisi konten pesan.

Properti

text string (Wajib)

Petunjuk positif, yang menjelaskan konten, gaya, dan komposisi citra yang dihasilkan.

Panjang maksimum adalah 800 karakter. Parameter ini mendukung bahasa Tiongkok dan Inggris. Setiap karakter Tiongkok, huruf, angka, atau simbol dihitung sebagai satu karakter. Karakter berlebih akan dipotong secara otomatis.

Contoh: Seekor kucing oranye duduk dengan ekspresi bahagia, hidup dan lucu, realistis dan akurat.

Catatan: Anda harus memberikan tepat satu elemen teks. Jika tidak, panggilan gagal.

parameters object (Opsional)

Parameter pemrosesan citra.

Properti

negative_prompt string (Opsional)

Prompt negatif yang menjelaskan konten yang tidak ingin Anda lihat dalam citra. Dapat digunakan untuk membatasi generasi citra.

Panjang maksimum adalah 500 karakter. Parameter ini mendukung bahasa Tiongkok dan Inggris. Karakter berlebih akan dipotong secara otomatis.

Contoh: resolusi rendah, kualitas rendah, anggota tubuh terdistorsi, jari terdistorsi, terlalu jenuh, tampilan seperti lilin, tidak ada detail wajah, terlalu halus, kesan buatan AI, komposisi kacau, teks buram, dan teks terdistorsi.

size string (Opsional)

Resolusi citra output dalam format width*height. Nilai default adalah 1664*928.

Resolusi yang tersedia beserta rasio aspeknya adalah:

  • 1664*928 (default): 16:9.

  • 1472*1104: 4:3.

  • 1328*1328: 1:1.

  • 1104*1472: 3:4.

  • 928*1664: 9:16.

n integer (Opsional)

Jumlah citra yang akan dihasilkan. Parameter ini saat ini tetap 1. Mengatur ke nilai lain menghasilkan kesalahan.

prompt_extend bool (Opsional)

Menentukan apakah akan mengaktifkan penulisan ulang prompt. Fitur ini hanya mengoptimalkan dan memperhalus petunjuk positif. Tidak mengubah prompt negatif.

  • true (default)

  • false

watermark bool (Opsional)

Menentukan apakah akan menambahkan watermark "Qwen-Image" di pojok kanan bawah citra. Nilai default adalah false. Watermark:

1

seed integer (Opsional)

Bilangan acak seed, dengan rentang nilai [0, 2147483647].

Menggunakan nilai parameter seed yang sama menghasilkan hasil yang lebih konsisten. Jika Anda tidak memberikan seed, algoritma menggunakan bilangan acak.

Catatan: Proses generasi model bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya tidak dijamin identik untuk setiap panggilan.

Parameter respons

Tugas berhasil

Data tugas, seperti status tugas dan URL citra, hanya disimpan selama 24 jam lalu secara otomatis dihapus. Anda harus segera menyimpan citra yang dihasilkan.

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
                        }
                    ]
                }
            }
        ],
        "task_metric": {
            "TOTAL": 1,
            "FAILED": 0,
            "SUCCEEDED": 1
        }
    },
    "usage": {
        "width": 1328,
        "image_count": 1,
        "height": 1328
    },
    "request_id": "7a270c86-db58-9faf-b403-xxxxxx"
}

Eksekusi tugas abnormal

Jika tugas gagal, respons menyertakan informasi kesalahan. Bidang kode dan pesan menunjukkan penyebab kesalahan. Untuk informasi lebih lanjut tentang cara mengatasi masalah, lihat Pesan kesalahan.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

Informasi output tugas.

Properti

choices array

Konten output yang dihasilkan model. Array ini hanya berisi satu elemen.

Properti

finish_reason string

Alasan tugas dihentikan. Nilai stop menunjukkan penyelesaian normal.

messages object

Pesan yang dikembalikan oleh model.

Properti

role string

Peran pesan. Ini tetap assistant.

content array

Properti

image string

URL citra yang dihasilkan dalam format PNG. Tautan berlaku selama 24 jam. Unduh dan simpan citra segera.

task_metric object

Statistik hasil tugas.

Properti

TOTAL integer

Jumlah total tugas.

SUCCEEDED integer

Jumlah tugas yang berhasil.

FAILED integer

Jumlah tugas yang gagal.

usage object

Statistik penggunaan untuk output. Hanya hasil yang berhasil yang dihitung.

Properti

image_count integer

Jumlah citra yang dihasilkan model. Saat ini tetap 1.

width integer

Lebar citra yang dihasilkan dalam piksel.

height integer

Tinggi citra yang dihasilkan dalam piksel.

request_id string

ID permintaan unik. Anda dapat menggunakan ID ini untuk melacak dan memecahkan masalah.

code string

Kode kesalahan. Parameter ini hanya dikembalikan ketika permintaan gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan.

message string

Pesan kesalahan terperinci. Parameter ini hanya dikembalikan ketika permintaan gagal. 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 disesuaikan untuk setiap bahasa. Untuk deskripsi parameter panggilan sinkron, lihat Pemanggilan HTTP.

Python

Catatan

Pastikan Anda telah menginstal versi terbaru SDK Python DashScope, jika tidak, kesalahan waktu proses dapat terjadi: Instal SDK.

Contoh permintaan
import json
import os
import dashscope
from dashscope import MultiModalConversation

# URL berikut 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-max",
    messages=messages,
    result_format='message',
    stream=False,
    watermark=False,
    prompt_extend=True,
    negative_prompt="low resolution, low quality, deformed limbs, deformed fingers, oversaturated, waxy, no facial details, overly smooth, AI-like, chaotic composition, blurry text, distorted text.",
    size='1664*928'
)

if response.status_code == 200:
    print(json.dumps(response, ensure_ascii=False))
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")
Contoh respons
URL citra berlaku selama 24 jam. Unduh citra 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

Catatan

Pastikan Anda telah menginstal versi terbaru SDK Java DashScope. Jika tidak, Anda mungkin mengalami kesalahan waktu proses. 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", "low resolution, low quality, deformed limbs, deformed fingers, oversaturated, waxy, no facial details, overly smooth, AI-like, chaotic composition, blurry text, distorted text.");
        parameters.put("size", "1664*928");

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(apiKey)
                .model("qwen-image-max")
                .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 citra berlaku selama 24 jam. Unduh citra 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

Penting

Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API asinkron.

Panggilan HTTP

Qwen-Image juga mendukung API asinkron. Alur panggilan HTTP terdiri dari dua langkah:

  1. Buat tugas untuk mendapatkan ID tugas: Kirim permintaan untuk membuat tugas. Respons mengembalikan ID tugas (task_id).

  2. Kueri hasil menggunakan ID tugas: Gunakan task_id untuk memeriksa status tugas hingga tugas selesai dan Anda mendapatkan URL citra.

Langkah 1: Buat tugas untuk mendapatkan ID tugas

Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Tiongkok (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

Catatan
  • Setelah tugas dibuat, gunakan task_id yang dikembalikan untuk mengkueri hasil. `task_id` berlaku selama 24 jam. Jangan membuat tugas duplikat. Sebagai gantinya, gunakan polling untuk mengambil hasil.

Parameter permintaan

Teks-ke-gambar

Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API asinkron.

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "qwen-image-plus",
    "input": {
        "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."
    },
    "parameters": {
        "negative_prompt":" ",
        "size": "1664*928",
        "n": 1,
        "prompt_extend": true,
        "watermark": false
    }
}'        

Header permintaan

Content-Type string (Wajib)

Tipe konten permintaan. Anda harus mengatur parameter ini ke application/json.

Authorization string (Wajib)

Kredensial otentikasi. API ini menggunakan Kunci API Model Studio untuk otentikasi. Contoh: `Bearer sk-xxxx`.

X-DashScope-Async string (Wajib)

Parameter ini digunakan untuk mengonfigurasi pemrosesan asinkron. Karena permintaan HTTP hanya mendukung pemrosesan asinkron, Anda harus mengatur parameter ini ke enable.

Penting

Jika Anda tidak menyertakan header permintaan ini, pesan kesalahan "current user api does not support synchronous calls" dikembalikan.

Body permintaan

model string (Wajib)

Nama model. Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API asinkron.

Contoh: qwen-image-plus.

input object (Wajib)

Informasi input dasar, seperti prompt.

Properti

prompt string (Wajib)

Petunjuk positif yang menjelaskan elemen dan fitur visual yang Anda inginkan dalam citra yang dihasilkan.

Panjang maksimum adalah 800 karakter. Parameter ini mendukung bahasa Tiongkok dan Inggris. Setiap karakter Tiongkok, huruf, angka, atau simbol dihitung sebagai satu karakter. Karakter berlebih akan dipotong secara otomatis.

Contoh: Seekor kucing oranye duduk dengan ekspresi bahagia, hidup dan lucu, realistis dan akurat.

negative_prompt string (Opsional)

Prompt negatif yang menjelaskan konten yang tidak ingin Anda lihat dalam citra. Dapat digunakan untuk membatasi generasi citra.

Panjang maksimum adalah 500 karakter. Parameter ini mendukung bahasa Tiongkok dan Inggris. Karakter berlebih akan dipotong secara otomatis.

Contoh: low resolution, low quality, deformed limbs, deformed fingers, oversaturated, waxy, no facial details, overly smooth, AI-like, chaotic composition, blurry text, distorted text.

parameters object (Opsional)

Parameter pemrosesan citra.

Properti

size string (Opsional)

Resolusi citra output dalam format width*height. Nilai default adalah 1664*928.

Resolusi yang tersedia beserta rasio aspeknya adalah:

  • 1664*928 (default): 16:9.

  • 1472*1104: 4:3.

  • 1328*1328: 1:1.

  • 1104*1472: 3:4.

  • 928*1664: 9:16.

n integer (Opsional)

Jumlah citra yang akan dihasilkan. Parameter ini saat ini tetap 1. Mengatur ke nilai lain menghasilkan kesalahan.

prompt_extend bool (Opsional)

Menentukan apakah akan mengaktifkan penulisan ulang prompt. Fitur ini hanya mengoptimalkan dan memperhalus petunjuk positif. Tidak mengubah prompt negatif.

  • true (default)

  • false

watermark bool (Opsional)

Menentukan apakah akan menambahkan watermark "Qwen-Image" di pojok kanan bawah citra. Nilai default adalah false. Watermark:

1

seed integer (Opsional)

Bilangan acak seed, dengan rentang nilai [0, 2147483647].

Menggunakan nilai parameter seed yang sama menghasilkan hasil yang lebih konsisten. Jika Anda tidak memberikan seed, algoritma menggunakan bilangan acak.

Catatan: Proses generasi model bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya tidak dijamin identik untuk setiap panggilan.

Parameter respons

Respons berhasil

Simpan `task_id` untuk mengkueri status dan hasil tugas.

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

Respons kesalahan

Pembuatan tugas gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan untuk mengatasi masalah.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

Informasi output tugas.

Properti

task_id string

ID tugas. Anda dapat menggunakan ID ini untuk mengkueri tugas hingga 24 jam.

task_status string

Status tugas.

Enumerasi

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

request_id string

ID permintaan unik. Anda dapat menggunakan ID ini untuk melacak dan memecahkan masalah.

code string

Kode kesalahan. Parameter ini hanya dikembalikan ketika permintaan gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan.

message string

Pesan kesalahan terperinci. Parameter ini hanya dikembalikan ketika permintaan gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan.

Langkah 2: Kueri 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}

Catatan
  • Rekomendasi polling: Model membutuhkan waktu sekitar 15 detik untuk berjalan. Kami merekomendasikan 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.

  • Alur status tugas: PENDING (dalam antrian) -> RUNNING (sedang diproses) -> SUCCEEDED (berhasil) / FAILED (gagal).

  • Tautan hasil: Setelah tugas berhasil, tautan citra dikembalikan. Tautan berlaku selama 24 jam. Anda harus segera mengunduh dan mentransfer citra ke storage space, seperti Object Storage Service (OSS).

Parameter permintaan

Kueri hasil tugas

Ganti 86ecf553-d340-4e21-xxxxxxxxx dengan ID tugas aktual.

Kunci API bersifat spesifik wilayah. Dapatkan Kunci API.
Untuk model di wilayah Beijing, ganti base_url dengan https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Header permintaan

Authorization string (Wajib)

Kredensial otentikasi. API ini menggunakan Kunci API Model Studio untuk otentikasi. Contoh: `Bearer sk-xxxx`.

Parameter jalur URL

task_id string (Wajib)

ID tugas.

Parameter respons

Tugas berhasil

Data tugas, seperti status tugas dan URL citra, hanya disimpan selama 24 jam lalu secara otomatis dihapus. Anda harus segera menyimpan citra yang dihasilkan.

{
    "request_id": "7434edb2-3cba-44e6-a772-xxxxxx",
    "output": {
        "task_id": "878f591e-ebdf-4e45-97eb-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-09-09 11:38:54.741",
        "scheduled_time": "2025-09-09 11:38:54.781",
        "end_time": "2025-09-09 11:39:19.484",
        "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/7d/xxx.png?Expires=xxxx"
            }
        ]
    },
    "usage": {
        "image_count": 1
    }
}

Tugas gagal

Jika tugas gagal, `task_status` diatur ke FAILED, dan kode serta pesan kesalahan disediakan. Untuk informasi lebih lanjut, lihat Pesan kesalahan untuk mengatasi masalah.

{
    "request_id": "c61fe158-c0de-40f0-b4d9-964625119ba4",
    "output": {
        "task_id": "86ecf553-d340-4e21-xxxxxxxxx",
        "task_status": "FAILED",
        "submit_time": "2025-11-11 11:46:28.116",
        "scheduled_time": "2025-11-11 11:46:28.154",
        "end_time": "2025-11-11 11:46:28.255",
        "code": "InvalidParameter",
        "message": "xxxxxxxx"
    }
}

output object

Informasi output tugas.

Properti

task_id string

ID tugas. Anda dapat menggunakan ID ini untuk mengkueri tugas hingga 24 jam.

task_status string

Status tugas.

Enumerasi

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

submit_time string

Waktu saat tugas diajukan. Waktu dalam UTC+8. Formatnya `YYYY-MM-DD HH:mm:ss.SSS`.

scheduled_time string

Waktu saat tugas mulai berjalan. Waktu dalam UTC+8. Formatnya `YYYY-MM-DD HH:mm:ss.SSS`.

end_time string

Waktu saat tugas selesai. Waktu dalam UTC+8. Formatnya `YYYY-MM-DD HH:mm:ss.SSS`.

results array

Daftar hasil tugas. Daftar ini mencakup URL citra, prompt, dan pesan kesalahan untuk sub-tugas yang gagal.

Struktur data

{
    "results": [
        {
            "orig_prompt": "",
            "actual_prompt": "",
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}

Properti

orig_prompt string

Prompt input asli.

actual_prompt string

Prompt aktual yang digunakan setelah penulisan ulang prompt diaktifkan. Bidang ini tidak dikembalikan jika penulisan ulang prompt dinonaktifkan.

url string

URL citra yang dihasilkan model. URL berlaku selama 24 jam. Unduh dan simpan citra segera.

code string

Kode kesalahan. Parameter ini hanya dikembalikan ketika permintaan gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan.

message string

Pesan kesalahan terperinci. Parameter ini hanya dikembalikan ketika permintaan gagal. Untuk informasi lebih lanjut, lihat Pesan kesalahan.

usage object

Statistik penggunaan untuk output. Hanya hasil yang berhasil yang dihitung.

Properti

image_count integer

Jumlah citra yang dihasilkan model. Saat ini tetap 1.

request_id string

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 implementasi SDK untuk setiap bahasa. Untuk deskripsi parameter pemanggilan asinkron, lihat Pemanggilan HTTP.

Karena model citra memerlukan waktu pemrosesan yang lama, layanan dasarnya bersifat asinkron. SDK membangun di atas ini dengan menyediakan dua mode pemanggilan berikut:

  • Panggilan sinkron (mode blocking): SDK secara otomatis menunggu tugas selesai lalu langsung mengembalikan hasil akhir. Pengalaman pemanggilan konsisten dengan panggilan sinkron biasa.

  • Panggilan asinkron (mode non-blocking): Panggilan segera mengembalikan ID tugas. Anda harus menggunakan ID ini untuk mengkueri status tugas dan hasil akhirnya.

SDK Python

Catatan

Pastikan Anda telah menginstal versi terbaru SDK Python DashScope, jika tidak, kesalahan waktu proses dapat terjadi: 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 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('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
                          model="qwen-image-plus", # Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API asinkron.
                          prompt=prompt,
                          negative_prompt=" ",
                          n=1,
                          size='1664*928',
                          prompt_extend=True,
                          watermark=False)
print(f'response: {rsp}')
if rsp.status_code == HTTPStatus.OK:
    # Simpan citra 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'sync_call Failed, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
Contoh respons
URL berlaku selama 24 jam. Unduh citra 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 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('----Creating Task----')
    task_info = create_async_task()
    print('----Polling Task Status----')
    poll_task_status(task_info)


# Buat tugas asinkron
def create_async_task():
    rsp = ImageSynthesis.async_call(api_key=api_key,
                                    model="qwen-image-plus", # Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API 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'Failed to create task, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
    return rsp


# Periksa 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 apakah melebihi batas waktu
        if time.time() - start_time > timeout:
            print('Polling timeout (1 minute), task not completed')
            return
            
        # Dapatkan status tugas
        status_rsp = ImageSynthesis.fetch(task)
        print(f'Task status query result: {status_rsp}')
        
        if status_rsp.status_code != HTTPStatus.OK:
            print(f'Failed to get task status, status_code: {status_rsp.status_code}, code: {status_rsp.code}, message: {status_rsp.message}')
            return
        task_status = status_rsp.output.task_status
        print(f'Current task status: {task_status}')
        
        if task_status == 'SUCCEEDED':
            print('Task completed, downloading image...')
            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'Image saved as: {file_name}')
            break
        elif task_status == 'FAILED':
            print(f'Task execution failed, status: {task_status}, code: {status_rsp.code}, message: {status_rsp.message}')
            break
        elif task_status == 'PENDING' or task_status == 'RUNNING':
            print('Task in progress, continue querying after 5 seconds...')
            time.sleep(5)
        else:
            print(f'Unknown task status: {task_status}, continue querying after 5 seconds...')
            time.sleep(5)

# Batalkan tugas asinkron, hanya tugas dalam 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'Failed to cancel task, status_code: {rsp.status_code}, code: {rsp.code}, message: {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 citra 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

Catatan

Pastikan Anda telah menginstal versi terbaru SDK Java DashScope. Jika tidak, Anda mungkin mengalami kesalahan waktu proses. Untuk informasi lebih lanjut, lihat Instal SDK.

Panggilan 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 {
        // URL berikut 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);
        parameters.put("negative_prompt", " ");
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(apiKey)
                        // Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API 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("---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));
    }

    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 citra 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
// 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 {
        // URL berikut 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("---Creating task----");
        String taskId = this.createAsyncTask();
        System.out.println("--Waiting for task to complete and return image url----");
        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)
                        // Saat ini, hanya model qwen-image-plus dan qwen-image yang mendukung panggilan API 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("Polling timed out (1 minute), task not completed");
                return;
            }

            try {
                ImageSynthesisResult result = imageSynthesis.fetch(taskId, apiKey);
                System.out.println("Task status query result: " + JsonUtils.toJson(result));
                if (result.getOutput() == null) {
                    System.out.println("Failed to get task status, output is empty");
                    return;
                }
                String taskStatus = result.getOutput().getTaskStatus();
                System.out.println("Current task status: " + taskStatus);
                switch (taskStatus) {
                    case "SUCCEEDED":
                        System.out.println("Task completed");
                        System.out.println(JsonUtils.toJson(result));
                        return;
                    case "FAILED":
                        System.out.println("Task execution failed, status: " + taskStatus);
                        return;
                    case "PENDING":
                    case "RUNNING":
                        System.out.println("Task in progress, querying again in 5 seconds...");
                        Thread.sleep(interval);
                        break;
                    default:
                        System.out.println("Unknown task status: " + taskStatus + ", querying again in 5 seconds...");
                        Thread.sleep(interval);
                        break;
                }
            } catch (ApiException | NoApiKeyException e) {
                System.err.println("API call exception: " + e.getMessage());
                return;
            } catch (InterruptedException e) {
                System.err.println("Thread interruption exception: " + 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 citra 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

  • Untuk kuota gratis dan harga, lihat Harga model.

  • Untuk batas laju model, lihat Qwen (Qwen-Image).

  • Penagihan: Anda dikenai biaya berdasarkan jumlah citra yang berhasil dihasilkan. Panggilan model yang gagal atau kesalahan pemrosesan tidak dikenai biaya atau mengurangi kuota gratis.

Konfigurasi akses citra

Citra yang dihasilkan disimpan di OSS Alibaba Cloud. Setiap citra 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 citra. Tautan hanya berlaku selama 24 jam.

Jika bisnis Anda memiliki persyaratan keamanan tinggi dan tidak dapat mengakses tautan OSS Alibaba Cloud, Anda harus mengonfigurasi daftar putih untuk akses publik. Tambahkan nama domain berikut ke daftar putih Anda untuk mengakses tautan citra.

# 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.com

Kode kesalahan

Jika panggilan gagal, lihat Pesan kesalahan untuk troubleshooting.

FAQ

T: Haruskah saya mengaktifkan atau menonaktifkan prompt_extend?

J: Pertahankan parameter ini diaktifkan (pengaturan default) jika prompt input Anda sederhana atau jika Anda ingin model lebih kreatif. Atur 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, qwen-image-max, dan qwen-image-edit?

J:

  • Model teks-ke-gambar: Menghasilkan citra dari deskripsi teks.

    • qwen-image-max dan qwen-image-max-2025-12-30: Kedua model saat ini memiliki kemampuan yang sama. Dibandingkan dengan qwen-image-plus, model ini meningkatkan realisme dan kealamian citra yang dihasilkan serta tampil lebih baik dalam rendering tekstur karakter, detail halus, dan teks.

    • qwen-image dan qwen-image-plus: Kedua model saat ini memiliki kemampuan yang sama, tetapi qwen-image-plus lebih hemat biaya.

    • qwen-image-plus-2026-01-09: Versi snapshot baru dari model generasi citra Qwen. Ini adalah versi distilasi dan dipercepat dari qwen-image-max dan mendukung generasi cepat citra berkualitas tinggi.

  • Model pengeditan citra:
    qwen-image-edit: Melakukan operasi seperti generasi citra-ke-citra dan modifikasi lokal berdasarkan citra input dan instruksi teks. Untuk informasi lebih lanjut, lihat Qwen - pengeditan citra.