1+ import http .client
2+ import json
3+ import requests
4+ import base64
5+
6+ # 配置全局变量
7+ API_URL = "www.dmxapi.cn" # API 节点
8+ DMX_API_TOKEN = "sk-XXXXXXXXXXXXX" # API 密钥
9+
10+ # 获取图片的base64编码
11+ def get_image_base64 (image_path ):
12+ with open (image_path , "rb" ) as image_file :
13+ return base64 .b64encode (image_file .read ()).decode ("utf-8" )
14+
15+ # 从URL获取图片并转换为base64格式
16+ def url_image_to_base64 (image_url ):
17+ """
18+ 从URL获取图片并转换为base64格式
19+
20+ 参数:
21+ image_url (str): 图片的URL地址
22+
23+ 返回:
24+ str: base64编码的图片字符串
25+ """
26+ try :
27+ # 发送GET请求获取图片
28+ response = requests .get (image_url )
29+
30+ # 将图片内容编码为base64
31+ image_binary = response .content
32+ base64_encoded = base64 .b64encode (image_binary ).decode ('utf-8' )
33+
34+ return base64_encoded
35+
36+ except Exception as e :
37+ print (f"获取图片失败: { str (e )} " )
38+ return None
39+
40+ # 提交图生图任务
41+ def midjourney_generate_image (image_path ):
42+
43+ # 获取图片的base64编码
44+ if image_path .startswith ('https://' ) or image_path .startswith ('http://' ):
45+ base64_string = url_image_to_base64 (image_path )
46+ else :
47+ base64_string = get_image_base64 (image_path )
48+
49+ conn = http .client .HTTPSConnection (API_URL )
50+ payload = json .dumps ({
51+ "mode" : "RELAX" , # 模式 可选值:"Turbo"、"Fast"(默认)、"Relax"
52+ "botType" : "NIJI_JOURNEY" , # 模型类型,可选值 "MID_JOURNEY"(默认) 或者 "NIJI_JOURNEY"
53+ "prompt" : "这是一个视频截图,请生成对应的吉卜力风格的图片" , # 提示词,描述希望生成的图片内容
54+ "base64Array" : [
55+ "data:image/png;base64," + base64_string # 包含图片 base64 数据的数组,格式为 "data:image/png;base64,<base64字符串>"
56+ ],
57+ "notifyHook" : "string" # 回调通知的 URL,处理完成后会向该地址发送回调
58+ })
59+
60+ # 设置请求头,包含认证信息和内容类型
61+ headers = {
62+ 'Authorization' : f'Bearer { DMX_API_TOKEN } ' ,
63+ 'Content-Type' : 'application/json'
64+ }
65+ # 发送POST请求到/mj/submit/imagine接口
66+ conn .request ("POST" , "/mj/submit/imagine" , payload , headers )
67+ # 获取响应
68+ res = conn .getresponse ()
69+ data_json = json .loads (res .read ().decode ("utf-8" ))
70+ # print(data_json)
71+ print (data_json ["description" ])
72+ task_id = data_json ["result" ]
73+ return task_id
74+
75+ if __name__ == "__main__" :
76+ # image_path = "/Users/dmxapi/Desktop/dxmapi.jpg" # 本地图片方式生成
77+ image_url = "https://cdn.klingai.com/bs2/upload-kling-api/8089468206/image/Cl6kH2gHPegAAAAABUwweg-0_raw_image_0.png" # url 图片方式生成
78+ print (midjourney_generate_image (image_url ))
0 commit comments