Midjourney 上传图片到 discord API接口
接口地址
https://www.dmxapi.cn/mj/submit/upload-discord-images
示例代码
python
import base64
import json
import requests
import os
def upload_image(api_key: str, image_path: str):
"""
将本地图片转换为Base64并上传到DMXAPI。
参数:
api_key (str): 您的 DMXAPI 令牌 (sk-...).
image_path (str): 本地图片的完整路径 (例如: 'c:\\nezha1.png').
返回:
dict: API返回的JSON数据,如果失败则返回 None。
"""
# --- 1. 检查文件是否存在 ---
if not os.path.exists(image_path):
print(f"错误:文件不存在 -> {image_path}")
return None
# --- 2. 将图片文件转换为 Base64 编码 ---
try:
with open(image_path, "rb") as image_file:
# 读取文件二进制内容
image_data = image_file.read()
# Base64 编码
base64_encoded_data = base64.b64encode(image_data)
# 解码为 utf-8 字符串
base64_string = base64_encoded_data.decode('utf-8')
except Exception as e:
print(f"错误:读取或转换文件时出错 -> {e}")
return None
# --- 3. 准备 API 请求 ---
# API 配置
url = "https://www.dmxapi.cn/mj/submit/upload-discord-images"
# 根据文件扩展名确定MIME类型 (更稳健的方式)
file_extension = os.path.splitext(image_path)[1].lower()
mime_type = "image/png" # 默认为 png
if file_extension == ".jpg" or file_extension == ".jpeg":
mime_type = "image/jpeg"
elif file_extension == ".gif":
mime_type = "image/gif"
elif file_extension == ".webp":
mime_type = "image/webp"
# 构建符合 API 要求的 Base64 字符串
formatted_base64 = f"data:{mime_type};base64,{base64_string}"
# 请求参数
payload = {
"mode": "RELAX",
"base64Array": [formatted_base64]
}
# 请求头设置
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
# --- 4. 发送 POST 请求 ---
print("正在向 API 发送请求...")
try:
# 使用 json=payload 会让 requests 库自动处理序列化和 Content-Type 头
response = requests.post(url, headers=headers, json=payload)
# 检查请求是否成功 (状态码 2xx)
response.raise_for_status()
print("请求成功!")
# 返回 JSON 格式的响应内容
return response.json()
except requests.exceptions.HTTPError as errh:
print(f"Http 错误: {errh}")
print(f"响应内容: {response.text}")
except requests.exceptions.ConnectionError as errc:
print(f"连接错误: {errc}")
except requests.exceptions.Timeout as errt:
print(f"超时错误: {errt}")
except requests.exceptions.RequestException as err:
print(f"请求发生未知错误: {err}")
return None
# --- 如何使用这个函数 ---
# 1. 设置你的 API 密钥和图片路径
MY_API_KEY = "sk-**********************************************" # 替换成你的 DMXAPI 令牌
IMAGE_FILE_PATH = r"c:\nezha1.png" # 使用 r"..." 可以避免反斜杠问题
# 2. 调用函数
api_result = upload_image(api_key=MY_API_KEY, image_path=IMAGE_FILE_PATH)
# 3. 处理返回结果
if api_result:
print("\n--- API 响应结果 ---")
# 使用 json.dumps 美化输出
print(json.dumps(api_result, indent=4, ensure_ascii=False))
返回示例
json
{
"code": 1,
"description": "success",
"result": [
"https://cdn.discordapp.com/attachments/1372468820912115716/1411054734671876268/image_1756492064613731046.jpg?ex=68b342a0&is=68b1f120&hm=3f572bef365d1b271ee5557d6edc40d90a654dc076510cc5f657ef277a19b561&"
]
}