Text-to-Image API を使用して、テキストの説明から新しい画像を生成します。Alibaba Cloud Model Studio は、2 つのモデルファミリーを提供しています。
Qwen-Image:複雑な中国語と英語のテキストのレンダリングに優れています。
Wan シリーズ:リアルな画像と写真品質の視覚効果を生成します。
モデルのパフォーマンス
Qwen-Image
複雑なテキスト
| 長文
| 複雑なレイアウト
|
ポスター作成
| イラストデザイン
| 写実的な写真
|
Wan
ポートレート写真
| 写実的
| アートスタイル
|
テキストレンダリング
| ポスターデザイン
| 複数画像生成
|
サポートされるモデル
モデルの選択
複雑なテキストのレンダリング (例:ポスター、対聯):
qwen-image-2.0-proまたはwan2.6-t2iを使用します。リアルなシーンと写真スタイル (一般的な使用):
wan2.6-t2iやwan2.5-t2i-previewなどの Wan モデルを選択します。カスタム出力画像の解像度:
qwen-image-2.0シリーズまたは Wan モデルを使用します。qwen-image-2.0 シリーズはカスタムの幅と高さをサポートします。総ピクセル数は 512*512 から 2048*2048 の間である必要があります。wan2.6-t2iなどの Wan モデルは、1280*1280 から 1440*1440 の間の総ピクセル数をサポートします。qwen-image-max および qwen-image-plus シリーズは、1664*928 (16:9)、928*1664 (9:16)、1328*1328 (1:1)、1472*1104 (4:3)、1104*1472 (3:4) の 5 つの固定サイズのみをサポートします。
はじめに
前提条件
API を呼び出す前に、API キーを取得してください。次に、API キーを環境変数として設定します。DashScope SDK を使用する場合は、SDK もインストールしてください。
サンプルコード
呼び出しメソッド:
すべての Qwen Text-to-Image モデルは同期呼び出しをサポートします。qwen-image-plus および qwen-image モデルは非同期呼び出しもサポートします。詳細については、「Qwen - text-to-image」をご参照ください。
すべての Wan Text-to-Image モデルは非同期呼び出しをサポートします。wan2.6-t2i モデルは同期呼び出しもサポートします。詳細については、「Wan - text-to-image V2」をご参照ください。
同期
Python
リクエスト例
import json
import os
import dashscope
from dashscope import MultiModalConversation
# シンガポールリージョンではこの URL を使用します。北京リージョンの場合は、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."}
]
}
]
# API キーは北京リージョンとシンガポールリージョンで異なります。API キーの取得:https://www.alibabacloud.com/help/model-studio/get-api-key
# 環境変数を設定していない場合は、以下の行を api_key="sk-xxx" に置き換えてください
api_key = os.getenv("DASHSCOPE_API_KEY")
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-2.0-pro",
messages=messages,
result_format='message',
stream=False,
watermark=False,
prompt_extend=True,
negative_prompt="Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
size='2048*2048'
)
if response.status_code == 200:
print(json.dumps(response, ensure_ascii=False))
else:
print(f"HTTP status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
print("See documentation: https://www.alibabacloud.com/help/model-studio/error-code")
レスポンス例
画像 URL は 24 時間後に有効期限が切れます。速やかに画像をダウンロードしてください。
{
"status_code": 200,
"request_id": "d2d1a8c0-325f-9b9d-8b90-xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"width": 2048,
"image_count": 1,
"height": 2048
}
}Java
リクエスト例
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 {
// シンガポールリージョンではこの URL を使用します。北京リージョンの場合は、https://dashscope.aliyuncs.com/api/v1 に置き換えてください
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// API キーは北京リージョンとシンガポールリージョンで異なります。API キーの取得:https://www.alibabacloud.com/help/model-studio/get-api-key
// 環境変数を設定していない場合は、以下の行を static String apiKey="sk-xxx" に置き換えてください
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("text", "Healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass, adorned with decorative elements such as birds and stars. The main title “Come Play Ball!” is prominently displayed at the top in bold, blue cartoon font. Below it, the subtitle “Come [Show Off Your Skills]!” appears in green font. A speech bubble adds playful charm with the text: “Hehe, watch me amaze my little friends next!” At the bottom, supplementary text reads: “We get to play ball with our friends again!” The color palette centers on fresh greens and blues, accented with bright pink and yellow tones to highlight a cheerful, childlike atmosphere.")
)).build();
Map<String, Object> parameters = new HashMap<>();
parameters.put("watermark", false);
parameters.put("prompt_extend", true);
parameters.put("negative_prompt", "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.");
parameters.put("size", "2048*2048");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-2.0-pro")
.messages(Collections.singletonList(userMessage))
.parameters(parameters)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
call();
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
レスポンス例
画像 URL は 24 時間後に有効期限が切れます。速やかに画像をダウンロードしてください。
{
"requestId": "5b6f2d04-b019-40db-a5cc-xxxxxx",
"usage": {
"image_count": 1,
"width": 2048,
"height": 2048
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
}
}curl
リクエスト例
curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "qwen-image-2.0-pro",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"text": "A winter street scene in Beijing featuring two adjacent traditional Chinese shops with gray-tiled roofs and vermilion-red exterior walls standing side by side. Warm-glow lanterns adorned with paper-cut horse motifs hang beneath the eaves, casting soft halos under overcast diffused light that gently reflects off the damp cobblestone pavement. On the left is a calligraphy shop: an aged indigo signboard bears the bold running-script characters “Text Rendering.” A vertical scroll on the storefront glass reads from top to bottom in Tian Yingzhang’s hard-pen style: “Professional Slides, Bilingual Posters, Advanced Infographics,” stamped with a cinnabar seal reading “1k token.” Inside, three vertically mounted calligraphy works are faintly visible on the wall—the first says “Alibaba,” the second “Qwen,” and the third “Image Generation.” An elderly white-haired man stands with his back to the camera, admiring the art. On the right is a flower shop whose sign spells out “Realistic Texture” using fresh blooms. Multi-tiered shelves inside display red roses, pink peonies, and greenery. A circular floral-patterned badge on the door reads “2k resolution,” and a colorful neon sign at the entrance displays the text “Detailed Depiction: People, Nature, Architecture.” Between the two shops sits a snowman holding an old-fashioned chalkboard with the words “Qwen-Image-2.0 Officially Released” scrawled in chalk. On the left side of the street, a young couple leans close together—the woman has a slender face, wears a beige cashmere coat and nude-toned sheer tights, and holds a transparent heart-shaped balloon printed with white text: “Image Generation and Editing in One.” Inside the balloon is a fluffy capybara plush toy. The man wears a well-tailored dark gray wool overcoat layered over a light turtleneck sweater. On the right side of the street, a delivery rider speeds past with “Smaller Model, Faster Speed” written across his back. The entire street blends dynamic motion with serene stillness through interwoven light and shadow."
}
]
}
]
},
"parameters": {
"negative_prompt": "Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
"prompt_extend": true,
"watermark": false,
"size": "2048*2048"
}
}'curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "qwen-image-2.0-pro",
"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, distorted limbs, malformed fingers, oversaturated colors, wax-figure appearance, lack of facial detail, excessive smoothness, AI-looking artifacts, chaotic composition, blurry or warped text.",
"prompt_extend": true,
"watermark": false,
"size": "2048*2048"
}
}'レスポンス例
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"content": [
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"
}
],
"role": "assistant"
}
}
]
},
"usage": {
"height": 2048,
"image_count": 1,
"width": 2048
},
"request_id": "d0250a3d-b07f-49e1-bdc8-6793f4929xxx"
}非同期
SDK は下位レベルで非同期ロジックをラップします。そのトップレベルのインターフェイスは、同期呼び出し (単一のリクエスト、最終結果を待機) のように動作します。curl の例では、タスクを送信するための API と結果をクエリするための API の 2 つの別々の非同期 API を使用します。
Python
リクエスト例
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# シンガポールリージョンの URL。base_url はリージョンによって異なります。
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# DASHSCOPE_API_KEY が設定されていない場合は、api_key="sk-xxx" に置き換えてください
# API キーはリージョンによって異なります。https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
api_key = os.getenv("DASHSCOPE_API_KEY")
message = Message(
role="user",
content=[
{
'text': 'A flower shop with exquisite windows, a beautiful wooden door, and flowers on display'
}
]
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print(rsp)
レスポンス例
URL は 24 時間有効です。速やかにダウンロードしてください。
{
"status_code": 200,
"request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"audio": null,
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}Java
リクエスト例
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;
public class Main {
static {
// シンガポールリージョンの URL。base_url はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// DASHSCOPE_API_KEY が設定されていない場合は、apiKey="sk-xxx" に置き換えてください
// API キーはリージョンによって異なります。https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call, please wait a moment----");
result = imageGeneration.call(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
basicCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}レスポンス例
URL は 24 時間有効です。速やかにダウンロードしてください。
{
"status_code": 200,
"request_id": "50b57166-eaaa-4f17-b1e0-35a5ca88672c",
"code": "",
"message": "",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}curl
非同期呼び出しの場合は、ヘッダーパラメーター
X-DashScope-Asyncをenableに設定します。非同期タスクの
task_idは 24 時間後に有効期限が切れます。有効期限が切れると、タスクのステータスはUNKNOWNになります。
ステップ 1:タスクの送信
このリクエストはタスク ID (task_id) を返します。
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'X-DashScope-Async: enable' \
--data '{
"model": "wan2.6-t2i",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"text": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display"
}
]
}
]
},
"parameters": {
"prompt_extend": true,
"watermark": false,
"n": 1,
"negative_prompt": "",
"size": "1280*1280"
}
}'ステップ 2:タスク ID を使用して結果をクエリする
ステップ 1 の task_id を使用します。task_status が SUCCEEDED または FAILED になるまで、タスクのステータスをポーリングします。
前の API 呼び出しで返された task_id の値で {task_id} を置き換えます。task_id は 24 時間以内のクエリで有効です。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"主要機能
1. 指示への追従 (プロンプト)
パラメーター: input.prompt (必須) と input.negative_prompt (任意)。
プロンプト (肯定的なプロンプト):画像に含めたい要素 (主題、シーン、スタイル、ライティング、構図など) を記述します。これは Text-to-Image の中核となる制御パラメーターです。
ネガティブプロンプト:画像に含めたくない要素 (「ぼやけた」や「指が多い」など) を記述します。出力品質の調整にのみ使用されます。
記述のヒント:構造化プロンプトを使用すると、より良い結果が得られることがよくあります。ベストプラクティスについては、「Text-to-Image プロンプトガイド」をご参照ください。
2. プロンプトリライトの有効化
パラメーター: parameters.prompt_extend (ブール値、デフォルト: true)。
この機能は、短いプロンプトを自動的に拡張・洗練させることで、画像品質を向上させます。有効にすると、大規模言語モデルがテキストをリライトするために必要な時間として、3~5 秒のレイテンシーが追加されます。
実用的なアドバイス:
入力プロンプトが短い、または一般的である場合に有効にします。これにより、画像品質が大幅に向上します。
詳細を厳密に制御する必要がある場合、すでに詳細な説明を提供している場合、または低レイテンシーが求められる場合に無効にします。
prompt_extendをfalseに設定します。
3. 出力画像の解像度設定
パラメーター: parameters.size (文字列)、フォーマット: "width*height"。
qwen-image-2.0 シリーズ:カスタムの幅と高さをサポートします。総ピクセル数は 512*512 から 2048*2048 の範囲内である必要があります。デフォルトの解像度は 2048*2048 です。推奨解像度:
2688*1536:16:91536*2688:9:162048*2048(デフォルト):1:12368*1728:4:31728*2368:3:4
qwen-image-max および qwen-image-plus シリーズ:以下の 5 つの固定解像度のみをサポートします:
1664*928(デフォルト):16:91472*1104:4:31328*1328:1:11104*1472:3:4928*1664:9:16
Wan V2 モデル (バージョン 2.0 以降):幅と高さは [512, 1440] ピクセルの範囲内でサポートされ、総ピクセル数は 1440*1440 を超えないようにする必要があります。一般的な解像度:
1024*1024(デフォルト):1:11440*810:16:9810*1440:9:161440*1080:4:31080*1440:3:4
本番環境への適用
耐障害性
レート制限への対応: API がエラーコード
Throttlingまたは HTTP ステータスコード 429 を返した場合、リクエストはレート制限されています。詳細については、「レート制限」をご参照ください。非同期タスクのポーリング: 非同期タスクの結果をポーリングする際は、レート制限のトリガーを避けるために、合理的な戦略 (最初の 30 秒間は 3 秒ごと、その後は間隔を広げるなど) を使用してください。最終的なタイムアウト (例: 2 分) を設定します。タスクがタイムアウトした場合は、失敗としてマークしてください。
リスク防止
永続ストレージ: API から返されるイメージ URL は 24 時間後に有効期限が切れます。本番システムでは、URL を受信後すぐにイメージをダウンロードし、永続ストレージ (例: Alibaba Cloud Object Storage Service) に保存する必要があります。
コンテンツのモデレーション: すべての
promptおよびnegative_promptの入力はモデレーションの対象となります。コンテンツがポリシーに違反した場合、リクエストはブロックされ、エラーDataInspectionFailedが返されます。著作権およびコンプライアンスリスク: ご利用のプロンプトが、適用される法令を遵守していることを確認してください。ブランドの商標、著名人の肖像、または著作権で保護された IP を含むコンテンツを生成すると、侵害リスクが生じる可能性があります。これらのリスクについては、お客様が責任を負うものとします。
API リファレンス
課金とレート制限
エラーコード
モデルの呼び出しに失敗してエラーメッセージが返された場合は、解決方法については、「エラーメッセージ」をご参照ください。
よくある質問
Q: イメージの URL はどのくらい有効ですか? イメージを永続的に保存するにはどうすればよいですか?
A: イメージの URL は 24 時間で有効期限切れになります。URL を受信した直後にイメージをダウンロードし、永続ストレージ(例:ローカルサーバーまたは Alibaba Cloud Object Storage Service)に保存してください。
Q: API 呼び出しで DataInspectionFailed が返されます。どのように対処すればよいですか?
A: このエラーは、入力テキストがコンテンツモデレーションに該当したことを意味します。プロンプトまたは negative_prompt の内容を確認・修正し、潜在的に非準拠となる可能性のある表現を削除したうえで、再度リトライしてください。
Q: prompt_extend パラメーターは有効にするべきですか、無効にするべきですか?
A: プロンプトが簡潔な場合、またはモデルによる創造的な詳細追加を期待する場合は、有効(デフォルト)のままにしてください。一方、プロンプトがすでに詳細に記述されている場合、あるいは厳密なレイテンシ制御が必要な場合は、prompt_extend を false に設定して無効化してください。
Q: イメージ内のテキストレンダリングを向上させるにはどうすればよいですか?
A: qwen-image-2.0-pro モデルをご利用ください。このモデルはテキストレンダリングに優れています。











