跳到主要内容Midjourney Imagine API 申请与实战指南 | 极客日志PythonNode.jsAI
Midjourney Imagine API 申请与实战指南
综述由AI生成Midjourney Imagine API 集成指南涵盖从申请凭证到实际调用的全流程。文档详细解析了基础文本生图、图像放大与变换、垫图改写、多图融合及局部重绘等核心功能。提供了 Python、Node.js 及 Curl 的代码示例,并介绍了异步 Webhook 回调与流式输出机制,帮助开发者高效实现 AI 绘图能力的业务落地。
MqEngine17 浏览 Midjourney Imagine API 申请与实战指南
Midjourney 作为业界领先的 AI 绘图工具,能以极快的速度生成高质量图像。通过其 Imagine API,我们可以将这一能力集成到自己的应用中,实现文本到图像的自动化生成。
本文档将详细介绍 API 的申请流程、基础调用、高级功能(如局部重绘、流式输出)以及代码示例。
申请流程
要使用 Midjourney Imagine API,需访问官方平台页面点击「Acquire」按钮获取凭证。首次申请通常包含免费额度。
若未登录,系统会自动跳转至注册/登录页,完成认证后返回即可。
基本使用
在界面填写必要参数即可发起请求。初次使用至少需要配置以下两项:
- authorization:从下拉列表中选择已申请的凭证。
- prompt:图片描述词。建议使用英文以获得更精准的效果,例如
Lamborghini speeds inside a volcano。
界面右侧通常会提供可直接复制的调用代码或「Try」测试按钮。
主要请求参数
prompt:图片描述词(支持自动翻译)。
mode:生成模式,可选 fast/relax/turbo,默认为 fast。
timeout:超时时间(秒),超时直接返回。
translation:是否自动翻译非英文 prompt。
split_images:是否将 2x2 结果拆分返回单张。
action/image_id:对历史图片继续操作时需指定。
callback_url:异步回调地址。
响应结构
调用成功后会返回 JSON 数据,关键字段说明如下:
{
"task_id": "唯一任务 ID",
"image_id": "图片唯一标识,用于后续变换操作",
"image_url": "缩略图 URL,可直接查看效果",
"raw_image_url": "原图 URL,清晰度更高但加载较慢",
"actions": ["upscale1", "variation1", ...
]
,
"success"
:
true
}
其中 actions 数组列出了可执行的操作,如 upscale(放大)和 variation(变换)。例如 upscale1 表示放大左上角第一张图,variation3 表示基于左下角第三张图进行变换。
图像放大与变换
针对生成的图片进行微调时,只需传入对应的 action 和 image_id。
例如,若想对右上角第二张图片进行变换,设置 action 为 variation2 并传递当前 image_id。再次调用后,API 会返回新的四张变体图。
若需精细化放大,可选择第四张图,传入 action: upscale4。注意,upscale 操作通常比 variation 耗时更短。
upscale_2x / upscale_4x:放大 2 倍或 4 倍。
zoom_out_2x / zoom_out_1_5x:缩小画面以展示周围区域。
pan_left/right/up/down:向不同方向偏移画面。
图像改写(垫图)
API 支持图像改写(Image Prompt),即输入一张图片 URL 及描述文字,基于原图风格生成新内容。
注意:输入的图片 URL 必须是纯图片链接,建议使用图床上传。
构造 prompt 时,将图片 URL 放在最前,后接空格和描述文字。可使用 --iw 参数调整图片权重。
https://example.com/image.jpg an illustration of a car parked on the beach --iw2
将上述整体传递给 prompt 字段,即可得到融合场景的新图。
图像融合
支持传入多张图片 URL 以实现融合效果。最多支持 5 张图片。
格式与垫图类似,将多个图片 URL 用空格分隔,最后跟上文字描述:
https://img1.jpg https://img2.jpg The bear is holding the chainsaw --iw2
局部变换(Inpainting)
该 API 支持局部重绘,需传入生成图片的 image_id、掩码(mask)及重绘行为参数 action。
获取掩码
掩码是通过灰度图片 Base64 编码得到的。开发者需自行编写工具绘制掩码区域(白色区域为重绘区),并确保尺寸与原图一致。
以下是 Python 获取掩码的参考逻辑(需根据实际环境调整依赖):
import sys
import os
from PySide6.QtWidgets import *
from PySide6.QtGui import QPainter, QMouseEvent, QPen, QColor, QImage
from PySide6.QtCore import Qt, QPoint
class DrawingWidget(QWidget):
def __init__(self, imagePath):
super().__init__()
self.setAttribute(Qt.WA_StaticContents)
self.background_image = QImage(imagePath)
imageSize = self.background_image.size() * 0.8
self.setFixedSize(imageSize)
self.foreground_image = QImage(self.size(), QImage.Format_ARGB32)
self.foreground_image.fill(Qt.transparent)
self.drawing = False
self.lastPoint = QPoint()
self.pen_color = QColor(255, 255, 255, 255)
self.pen_size = 50
def set_pen_size(self, size):
self.pen_size = size
def mousePressEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event: QMouseEvent):
if event.buttons() & Qt.LeftButton and self.drawing:
painter = QPainter(self.foreground_image)
painter.setRenderHint(QPainter.Antialiasing, True)
pen = QPen(self.pen_color, self.pen_size, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
painter.setPen(pen)
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton and self.drawing:
self.drawing = False
def paintEvent(self, event):
canvasPainter = QPainter(self)
canvasPainter.drawImage(self.rect(), self.background_image, self.background_image.rect())
canvasPainter.drawImage(self.rect(), self.foreground_image, self.foreground_image.rect())
def save_image(self, path):
self.foreground_image.save(path)
转换 Base64
获得掩码图片后,需将其转换为 Base64 编码以便传入 API。
import cv2
import base64
image_path = 'temp.jpg'
gray_image = cv2.imread(image_path)
_, buffer = cv2.imencode('.jpg', gray_image)
base64_encoded = base64.b64encode(buffer).decode('utf-8')
with open('grayscale_image_base64.txt', 'w') as f:
f.write(base64_encoded)
print("success!")
调用局部重绘
设置 action 为 variation_region,传入 image_id 和 mask。prompt 为非必填,但建议填写以明确重绘目标。
代码示例
平台页面通常会自动生成多种语言的代码片段。以下为部分语言示例。
CURL
curl -X POST 'https://api.acedata.cloud/midjourney/imagine' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{ "prompt": "A cute cat ", "action": "variation_region", "image_id": "1265875488702726144", "mask": "/9j/4AAQSkZJRgABAQAAAQABAAD/..." }'
Python
import requests
url = "https://api.acedata.cloud/midjourney/imagine"
headers = {
"accept": "application/json",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"prompt": "A cute cat ",
"action": "variation_region",
"image_id": "1265875488702726144",
"mask": "/9j/4AAQSkZJRgABAQAAAQABAAD/..."
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
异步回调
由于生图耗时较长,API 支持 Webhook 异步回调。当任务成功或失败时,结果会通过 HTTP 请求发送至指定的 callback_url。
- 搭建接收 HTTP 请求的服务端点。
- 在请求体中设置
callback_url。
- 提交任务后立即收到
task_id,无需等待。
- 生成完成后,服务端会收到包含
success、task_id、image_url 等字段的 JSON 数据。
若生成失败,success 将为 false,并附带 error.code 和 error.message 供排查。
流式输出
Midjourney 生图过程包含多次迭代,从模糊到清晰。默认模式下,API 仅在生图完成后返回最终结果。为提升体验,支持流式输出。
开启流式输出需修改请求头 accept 为 application/x-ndjson,并在客户端处理流式响应。
Python 示例
import requests
url = 'https://api.acedata.cloud/midjourney/imagine'
headers = {
'content-type': 'application/json',
'accept': 'application/x-ndjson',
'authorization': 'Bearer {token}'
}
body = {"prompt": "a beautiful cat --v 6"}
r = requests.post(url, headers=headers, json=body, stream=True)
for line in r.iter_lines():
print(line.decode())
Node.js 示例
const axios = require("axios");
const url = "https://api.acedata.cloud/midjourney/imagine";
const headers = {
"content-type": "application/json",
"accept": "application/x-ndjson",
"authorization": "Bearer {token}"
};
const body = {
prompt: "a beautiful cat --v 6",
action: "generate"
};
axios.post(url, body, { headers: headers, responseType: "stream" })
.then((response) => {
console.log(response.status);
response.data.on("data", (chunk) => {
console.log(chunk.toString());
});
})
.catch((error) => {
console.error(error);
});
流式输出中包含 progress 字段(0-100),可用于前端进度条展示。注意,生成未完成时 actions 为空,且中间生成的 image_url 会在完成后销毁。如需结合流式与异步回调,可同时指定 accept 头和 callback_url。
相关免费在线工具
- RSA密钥对生成器
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
- Mermaid 预览与可视化编辑
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
- 随机西班牙地址生成器
随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online