本文介绍通义万相-文本生成图像模型的输入输出参数。
相关指南:文本生成图像
模型概览
模型名 | 模型简介 | 免费额度 | 计费单价 | 限流(含主账号与RAM子账号) | |
任务下发接口QPS限制 | 同时处理中任务数量 | ||||
wanx-v1 | 通义万相-文本生成图像大模型。支持中英文双语输入。重点风格包括但不限于水彩、油画、中国画、素描、扁平插画、二次元、3D卡通、 摄影、人像写真。 | 免费额度:500张 领取方式:开通阿里云百炼大模型服务后,自动发放 有效期:180天 | 0.16元/张 | 2 | 1 |
前提条件
您需要已获取API Key并配置API Key到环境变量。如果通过SDK调用,还需要安装DashScope SDK。
HTTP调用
为了减少等待时间并且避免请求超时,服务采用异步方式提供。您需要发起两个请求:
创建任务:首先发送一个请求创建文生图任务,该请求会返回任务ID。
根据任务ID查询结果:使用上一步获得的任务ID,查询模型生成的结果。
创建任务
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
请求头(Headers) | 基础文生图curl
相似图片生成curl
|
Content-Type string 必选 请求内容类型。固定为 | |
Authorization string 必选 推荐您使用百炼API-Key,也可填DashScope API-Key。例如:Bearer d1xxx2a。 | |
X-DashScope-WorkSpace string 可选 API-KEY所属账号的工作空间。
| |
X-DashScope-Async string 必选 是否开启异步处理。必须开启异步处理,设置为 | |
请求体(Request Body) | |
model string 必选 调用模型。 | |
input object 必选 输入图像的基本信息,比如图像URL地址。 | |
parameters object 可选 图像处理参数。 |
响应 | 成功响应
异常响应
|
output object 任务输出信息。 | |
code string 请求失败,表示错误码,成功时返回参数中不会包含该参数。 | |
message string 请求失败,表示失败详细信息,成功时返回参数中不会包含该参数。 | |
request_id string 请求唯一标识。可用于请求明细溯源和问题排查。 |
根据任务ID查询结果
GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
本示例将$DASHSCOPE_API_KEY替换成自己的API-KEY,并将“tasks/”后面的字符串替换成task_id才能正常运行。
请求头(Headers) | 查询任务结果
|
Authorization string 必选 推荐使用百炼API-Key,也可填DashScope API-Key。例如:Bearer d1xxx2a。 | |
URL路径参数(Path parameters) | |
task_id string 必选 任务id。 |
响应 | 任务执行成功任务状态和结果将保留24小时,图像的URL也在此期间有效,请及时保存生成的图像。24小时后,任务和结果将被清除。
任务执行失败
任务部分失败
|
output object 调用结果信息。 | |
request_id string 请求唯一标识。可用于请求明细溯源和问题排查。 | |
usage object 输出信息统计。 |
(可选)配置域名白名单,允许访问图片链接
根据上述查询接口的响应,可以看到返回了图片OSS链接,如https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png
。图片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
SDK调用
请先确认已安装最新版SDK:安装SDK。
此API支持Python SDK和Java SDK。SDK接口的入参和出参可参考HTTP调用。
由于本模型请求处理时间较长,服务采用异步方式提供,SDK进行了封装。您既可以按异步方式调用,也可以按照同步方式调用。
同步调用模式
基础文生图
Python
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
def simple_call():
prompt = 'Mouse rides elephant'
rsp = ImageSynthesis.call(model=ImageSynthesis.Models.wanx_v1,
prompt=prompt,
n=4,
size='1024*1024')
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
print(rsp.usage)
# save file to current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
simple_call()
Java
请求示例:
// 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.task.AsyncTaskListParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void basicCall() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.model(ImageSynthesis.Models.WANX_V1)
.n(4)
.size("1024*1024")
.prompt("雄鹰自由自在的在蓝天白云下飞翔")
.build();
ImageSynthesisResult result = is.call(param);
System.out.println(result);
}
public static void listTask() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
ImageSynthesisListResult result = is.list(param);
System.out.println(result);
}
public void fetchTask() throws ApiException, NoApiKeyException {
String taskId = "your task id";
ImageSynthesis is = new ImageSynthesis();
// If set DASHSCOPE_API_KEY environment variable, apiKey can null.
ImageSynthesisResult result = is.fetch(taskId, null);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args){
try{
basicCall();
//listTask();
}catch(ApiException|NoApiKeyException e){
System.out.println(e.getMessage());
}
}
}
相似图片生成
Python
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
prompt = '玫瑰花海,背景是日出,采用淡紫色和粉红色的概念艺术装置风格,郁郁葱葱的风景,以及有序的布局'
ref_img = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png"
print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(model=ImageSynthesis.Models.wanx_v1,
prompt=prompt,
n=1,
style='<auto>',
size='1024*1024',
ref_img=ref_img)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# save file to current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
Java
package org.example.bailian.text2similarimage.sync;
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.JsonUtils;
public class Main {
public void syncCall() {
String prompt = "玫瑰花海,背景是日出,采用淡紫色和粉红色的概念艺术装置风格,郁郁葱葱的风景,以及有序的布局";
String refImage = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png";
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.model(ImageSynthesis.Models.WANX_V1)
.prompt(prompt)
.n(1)
.size("1024*1024")
.refImage(refImage)
.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){
Main text2Image = new Main();
text2Image.syncCall();
}
}
接口返回结果
任务执行成功
{
"status_code": 200,
"request_id": "b54ffeb8-6212-9dac-808c-b3771cba3788",
"code": null,
"message": "",
"output": {
"task_id": "996523eb-034d-459b-ac88-b340b95007a4",
"task_status": "SUCCEEDED",
"results": [
{"url": "RESULT_URL1"},
{"url": "RESULT_URL2"},
{"url": "RESULT_URL3"},
{"url": "RESULT_URL4"}
],
"task_metrics": {
"TOTAL": 4,
"SUCCEEDED": 4,
"FAILED": 0
}
},
"usage": {"image_count": 4}
}
数据格式错误
示例中看到有这类错误码信息InvalidParameter.DataInspection会一同和正常没有问题的URL一起返回,这属于正常现象,表示是当前这个提示错误信息的url数据检查错误,媒体格式不支持或不正确,可以重新发起请求再获取一张图片。
{
"status_code": 200,
"request_id": "b54ffeb8-6212-9dac-808c-b3771cba3788",
"code": null,
"message": "",
"output": {
"task_id": "996523eb-034d-459b-ac88-b340b95007a4",
"task_status": "SUCCEEDED",
"results": [
{"url": "RESULT_URL1"},
{"url": "RESULT_URL2"},
{
"code": "InvalidParameter.DataInspection",
"message": "Unable to download the media resource during the data inspection process."
},
{"url": "RESULT_URL4"}
],
"task_metrics": {
"TOTAL": 4,
"SUCCEEDED": 4,
"FAILED": 0
}
},
"usage": {"image_count": 4}
}
数据含有敏感信息
示例中看到有这类错误码信息DataInspectionFailed会一同和正常的url一起返回属于正常现象,数据检查错误,输出包含疑似敏感内容被绿网拦截。
{
"status_code": 200,
"request_id": "b54ffeb8-6212-9dac-808c-b3771cba3788",
"code": null,
"message": "",
"output": {
"task_id": "996523eb-034d-459b-ac88-b340b95007a4",
"task_status": "SUCCEEDED",
"results": [
{"url": "RESULT_URL1"},
{
"code": "DataInspectionFailed",
"message": "Output data may contain inappropriate content."
},
{"url": "RESULT_URL3"},
{"url": "RESULT_URL4"}
],
"task_metrics": {
"TOTAL": 4,
"SUCCEEDED": 4,
"FAILED": 0
}
},
"usage": {"image_count": 4}
}
异步调用模式
基础文生图
python
from http import HTTPStatus
from dashscope import ImageSynthesis
# 创建异步任务
def create_async_task():
rsp = ImageSynthesis.async_call(model=ImageSynthesis.Models.wanx_v1,
prompt='Eagle flying in blue sky',
n=4,
size='1024*1024')
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
print(rsp.usage)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# 获取异步任务信息
def fetch_task_status(task):
status = ImageSynthesis.fetch(task)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# 等待异步任务结束
def wait_task(task):
rsp = ImageSynthesis.wait(task)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# 取消异步任务,只有处于PENDING状态的任务才可以取消
def cancel_task(task):
rsp = ImageSynthesis.cancel(task)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
task_info = create_async_task()
fetch_task_status(task_info)
wait_task(task_info)
Java
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.JsonUtils;
public class Main {
public void asyncCall() {
System.out.println("---create task----");
String taskId = this.createAsyncTask();
System.out.println("---wait task done then return image url----");
this.waitAsyncTask(taskId);
}
/**
* 创建异步任务
* @return taskId
*/
public String createAsyncTask() {
String prompt = "少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光";
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.model(ImageSynthesis.Models.WANX_V1)
.prompt(prompt)
.n(1)
.size("1024*1024")
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
result = imageSynthesis.asyncCall(param);
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
String taskId = result.getOutput().getTaskId();
System.out.println("taskId=" + taskId);
return taskId;
}
/**
* 等待异步任务结束
* @param taskId 任务id
* */
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
// If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
result = imageSynthesis.wait(taskId, null);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result.getOutput()));
System.out.println(JsonUtils.toJson(result.getUsage()));
}
public static void main(String[] args){
Main main = new Main();
main.asyncCall();
}
}
相似图片生成
python
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
prompt = '少女,高分辨率,增加细节,细节强化,侧面视角,森林,奶油风,暖色调,精致的脸部比例,精细的裙子,五官立体,长卷发,极高分辨率,清晰度强化,全身像,微笑,五颜六色的花瓣飞舞,自然光'
ref_img = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png"
def async_call():
print('----create task----')
task_info = create_async_task()
print('----wait task done then save image----')
wait_async_task(task_info)
# 创建异步任务
def create_async_task():
rsp = ImageSynthesis.async_call(model=ImageSynthesis.Models.wanx_v1,
prompt=prompt,
n=1,
style='<auto>',
size='1024*1024',
ref_img=ref_img)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('create_async_task Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# 等待异步任务结束
def wait_async_task(task):
rsp = ImageSynthesis.wait(task)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
# save file to current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()
Java
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.JsonUtils;
public class Main {
public void asyncCall() {
System.out.println("---create task----");
String taskId = this.createAsyncTask();
System.out.println("---wait task done then return image url----");
this.waitAsyncTask(taskId);
}
/**
* 创建异步任务
* @return taskId
*/
public String createAsyncTask() {
String prompt = "玫瑰花海,背景是日出,采用淡紫色和粉红色的概念艺术装置风格,郁郁葱葱的风景,以及有序的布局";
String refImage = "https://huarong123.oss-cn-hangzhou.aliyuncs.com/image/%E7%8E%AB%E7%91%B0.png";
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.model(ImageSynthesis.Models.WANX_V1)
.prompt(prompt)
.n(1)
.size("1024*1024")
.refImage(refImage)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
result = imageSynthesis.asyncCall(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
String taskId = result.getOutput().getTaskId();
System.out.println("taskId=" + taskId);
return taskId;
}
/**
* 等待异步任务结束
* @param taskId 任务id
* */
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
// If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
result = imageSynthesis.wait(taskId, null);
} catch (ApiException|NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result.getOutput()));
System.out.println(JsonUtils.toJson(result.getUsage()));
}
public static void main(String[] args){
Main text2Image = new Main();
text2Image.asyncCall();
}
}
错误码
如果模型调用失败并返回报错信息,请参见错误码进行解决。