通义千问-图像编辑模型(qwen-image-edit)支持多图编辑,可精确修改图内文字、增删或移动物体、改变主体动作、迁移图片风格及增强画面细节。
效果展示
HTTP调用
在调用前,您需要获取API Key,再配置API Key到环境变量。
如需通过SDK进行调用,请安装DashScope SDK。目前,该SDK已支持Python和Java。
北京和新加坡地域拥有独立的 API Key 与请求地址,不可混用,跨地域调用将导致鉴权失败或服务报错。
北京地域:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
新加坡地域:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
请求参数 | 单图编辑以下为北京地域 URL ,若使用新加坡地域的模型,需将 URL 替换为:
多图融合以下为北京地域 URL ,若使用新加坡地域的模型,需将 URL 替换为:
|
请求头(Headers) | |
Content-Type 请求内容类型。此参数必须设置为 | |
Authorization 请求身份认证。接口使用阿里云百炼API-Key进行身份认证。示例值:Bearer sk-xxxx。 | |
请求体(Request Body) | |
model 模型名称,固定为 | |
input 输入参数对象,包含以下字段: | |
parameters 控制图像生成的附加参数。 |
响应参数 | 任务执行成功任务数据(如任务状态、图像URL等)仅保留24小时,超时后会被自动清除。请您务必及时保存生成的图像。
任务执行异常如果因为某种原因导致任务执行失败,将返回相关信息,可以通过code和message字段明确指示错误原因。请参见错误信息进行解决。
|
output 包含模型生成结果。 | |
usage 本次调用的资源使用情况,仅调用成功时返回。 | |
request_id 请求唯一标识。可用于请求明细溯源和问题排查。 | |
code 请求失败的错误码。请求成功时不会返回此参数,详情请参见错误信息。 | |
message 请求失败的详细信息。请求成功时不会返回此参数,详情请参见错误信息。 |
DashScope SDK调用
SDK 的参数命名与HTTP接口基本一致,参数结构根据语言特性进行封装,完整参数列表请参见通义千问 API 参考。
Python SDK调用
推荐安装最新版DashScope Python SDK,否则可能运行报错:安装或升级SDK。
不支持异步接口。
请求示例
通过公网URL传入图片
import json
import os
from dashscope import MultiModalConversation
import dashscope
# 以下为中国(北京)地域url,若使用新加坡地域的模型,需将url替换为:https://dashscope-intl.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
# 模型支持输入1-3张图片
messages = [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"},
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"},
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"},
{"text": "图1中的女生穿着图2中的黑色裙子按图3的姿势坐下"}
]
}
]
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
# 模型仅支持单轮对话,复用了多轮对话的接口
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-edit",
messages=messages,
stream=False,
watermark=False,
negative_prompt=" "
)
if response.status_code == 200:
# 如需查看完整响应,请取消下行注释
# print(json.dumps(response, ensure_ascii=False))
print("输出图像的URL:", response.output.choices[0].message.content[0]['image'])
else:
print(f"HTTP返回码:{response.status_code}")
print(f"错误码:{response.code}")
print(f"错误信息:{response.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
通过Base64编码传入图片
import json
import os
from dashscope import MultiModalConversation
import base64
import mimetypes
import dashscope
# 以下为中国(北京)地域url,若使用新加坡地域的模型,需将url替换为:https://dashscope-intl.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
# ---用于 Base64 编码 ---
# 格式为 data:{mime_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("不支持或无法识别的图像格式")
try:
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(
image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
except IOError as e:
raise IOError(f"读取文件时出错: {file_path}, 错误: {str(e)}")
# 获取图像的 Base64 编码
# 调用编码函数,请将 "/path/to/your/image.png" 替换为您的本地图片文件路径,否则无法运行
image = encode_file("/path/to/your/image.png")
messages = [
{
"role": "user",
"content": [
{"image": image},
{"text": "生成一张符合深度图的图像,遵循以下描述:一辆红色的破旧的自行车停在一条泥泞的小路上,背景是茂密的原始森林"}
]
}
]
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
# 模型仅支持单轮对话,复用了多轮对话的接口
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-edit",
messages=messages,
stream=False,
watermark=False,
negative_prompt=" "
)
if response.status_code == 200:
# 如需查看完整响应,请取消下行注释
# print(json.dumps(response, ensure_ascii=False))
print("输出图像的URL:", response.output.choices[0].message.content[0]['image'])
else:
print(f"HTTP返回码:{response.status_code}")
print(f"错误码:{response.code}")
print(f"错误信息:{response.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
通过URL下载图像
# 需要安装requests以下载图像: pip install requests
import requests
def download_image(image_url, save_path='output.png'):
try:
response = requests.get(image_url, stream=True, timeout=300) # 设置超时
response.raise_for_status() # 如果HTTP状态码不是200,则引发异常
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"图像已成功下载到: {save_path}")
except requests.exceptions.RequestException as e:
print(f"图像下载失败: {e}")
image_url = "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
download_image(image_url, save_path='output.png')
响应示例
图像链接的有效期为24小时,请及时下载图像。
input_tokens
和output_tokens
为兼容字段,当前固定为0。
{
"status_code": 200,
"request_id": "3daccb10-10ca-9399-8b6a-xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxx"
}
]
}
}
]
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"width": 1248,
"image_count": 1,
"height": 832
}
}
Java SDK调用
推荐安装最新版DashScope Java SDK,否则可能运行报错:安装或升级SDK。
请求示例
通过公网URL传入图片
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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class QwenImageEdit {
static {
// 以下为中国(北京)地域url,若使用新加坡地域的模型,需将url替换为:https://dashscope-intl.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey="sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {
MultiModalConversation conv = new MultiModalConversation();
// 模型支持输入1-3张图片
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/thtclx/input1.png"),
Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/iclsnx/input2.png"),
Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250925/gborgw/input3.png"),
Collections.singletonMap("text", "图1中的女生穿着图2中的黑色裙子按图3的姿势坐下")
)).build();
Map<String, Object> parameters = new HashMap<>();
parameters.put("watermark", false);
parameters.put("negative_prompt", " ");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-edit")
.messages(Collections.singletonList(userMessage))
.parameters(parameters)
.build();
MultiModalConversationResult result = conv.call(param);
// 如需查看完整响应,请取消下行注释
// System.out.println(JsonUtils.toJson(result));
System.out.println("输出图像的URL:" + result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("image"));
}
public static void main(String[] args) {
try {
call();
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
}
}
通过Base64编码传入图片
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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class QwenImageEdit {
static {
// 以下为中国(北京)地域url,若使用新加坡地域的模型,需将url替换为:https://dashscope-intl.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
}
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey="sk-xxx"
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void call() throws ApiException, NoApiKeyException, UploadFileException, IOException {
// 请将 "/path/to/your/image.png" 替换为您的本地图片文件路径,否则无法运行
String image = encodeFile("/path/to/your/image.png");
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", image),
Collections.singletonMap("text", "生成一张符合深度图的图像,遵循以下描述:一辆红色的破旧的自行车停在一条泥泞的小路上,背景是茂密的原始森林")
)).build();
Map<String, Object> parameters = new HashMap<>();
parameters.put("watermark", false);
parameters.put("negative_prompt", " ");
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(apiKey)
.model("qwen-image-edit")
.messages(Collections.singletonList(userMessage))
.parameters(parameters)
.build();
MultiModalConversationResult result = conv.call(param);
// 如需查看完整响应,请取消下行注释
// System.out.println(JsonUtils.toJson(result));
System.out.println("输出图像的URL:" + result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("image"));
}
/**
* 将文件编码为Base64字符串
* @param filePath 文件路径
* @return Base64字符串,格式为 data:{mime_type};base64,{base64_data}
*/
public static String encodeFile(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new IllegalArgumentException("文件不存在: " + filePath);
}
// 检测MIME类型
String mimeType = null;
try {
mimeType = Files.probeContentType(path);
} catch (IOException e) {
throw new IllegalArgumentException("无法检测文件类型: " + filePath);
}
if (mimeType == null || !mimeType.startsWith("image/")) {
throw new IllegalArgumentException("不支持或无法识别的图像格式");
}
// 读取文件内容并编码
byte[] fileBytes = null;
try{
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("无法读取文件内容: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void main(String[] args) {
try {
call();
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
}
}
通过URL下载图像
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownloader {
public static void downloadImage(String imageUrl, String savePath) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(300000);
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("图像已成功下载到: " + savePath);
} catch (Exception e) {
System.err.println("图像下载失败: " + e.getMessage());
}
}
public static void main(String[] args) {
String imageUrl = "http://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx?Expires=xxx";
String savePath = "output.png";
downloadImage(imageUrl, savePath);
}
}
响应示例
图像链接的有效期为24小时,请及时下载图像。
{
"requestId": "9e59e2da-28b0-9468-b356-5d2beea8a477",
"usage": {},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/xxx.png?Expires=xxxx"
}
]
}
}
]
}
}
计费与限流
北京地域
模型名称 | 计费单价 | 限流(主账号与RAM子账号共用) | 免费额度(查看) | |
每秒请求数(RPS)限制 | 同时处理中任务数量 | |||
qwen-image-edit | 0.3元/张 | 2 | 2 | 100张 |
新加坡地域
模型名称 | 计费单价 | 限流(主账号与RAM子账号共用) | 免费额度(查看) | |
每秒请求数(RPS)限制 | 同时处理中任务数量 | |||
qwen-image-edit | 0.330266/张 | 2 | 2 | 无免费额度 |
计费说明:
图像访问权限配置
模型生成的图像存储于阿里云OSS,每张图像会被分配一个OSS链接,如https://dashscope-result-xx.oss-cn-xxxx.aliyuncs.com/xxx.png
。OSS链接允许公开访问,可以使用此链接查看或者下载图片,链接仅在 24 小时内有效。
如果您的业务对安全性要求较高,无法访问阿里云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
错误码
如果模型调用失败并返回报错信息,请参见错误信息进行解决。
常见问题
Q: qwen-image-edit
支持多轮对话式编辑吗?
A: 不支持。qwen-image-edit
模型本身的设计是单轮执行,即每次调用都是一个独立的、无状态的编辑任务,不会记忆之前的编辑历史。若想实现连续编辑,需将上次编辑生成的图片作为新的输入图片,再次调用服务。
Q: 如何查看模型调用量?
A: 模型的调用信息存在小时级延迟,在模型调用完一小时后,请在模型观测(北京或新加坡)页面,查看调用量、调用次数、成功率等指标。如何查看模型调用记录