Z-Image-GGUF代码实例:curl命令调用API生成图片,附完整JSON示例
1. 项目简介与核心价值
如果你正在寻找一种不依赖复杂Web界面,直接用代码就能调用文生图AI模型的方法,那么你来对地方了。今天我们要聊的,就是如何通过简单的curl命令,直接与部署好的Z-Image-GGUF模型API进行对话,让它根据你的文字描述生成图片。
Z-Image是阿里巴巴通义实验室开源的一款文生图模型,能力相当不错。而我们今天用的GGUF量化版本,最大的好处就是对硬件要求更友好,让你用更普通的显卡也能跑起来。但很多人只知道通过WebUI点点按钮,却不知道背后其实有一套更灵活、更强大的API接口。
想象一下这些场景:你想把图片生成功能集成到自己的应用里;你需要批量处理几百张图片描述;或者你只是单纯喜欢用命令行搞定一切。这些时候,API调用就比手动点击高效太多了。
这篇文章,我就带你彻底搞懂怎么用curl命令调用Z-Image-GGUF的API,从最简单的示例到复杂的参数调整,我都会配上完整的JSON代码,你复制粘贴就能用。
2. 理解ComfyUI的API工作机制
在开始写命令之前,咱们先花两分钟搞明白ComfyUI的API是怎么工作的。这样你后面遇到问题,自己也能知道去哪儿找原因。
ComfyUI虽然是个可视化工具,但它底层提供了一套完整的HTTP API。你可以把它想象成一个餐厅:WebUI是给普通顾客用的菜单和点餐台,而API则是给合作伙伴用的订货电话。通过电话,你可以更程序化、更批量地下单。
这套API主要做两件事:
- 提交任务:你把生成图片的“配方”(也就是工作流和参数)发给它
- 获取结果:等图片生成好后,你再问它要成品
整个流程分三步走:
你的代码 --(1. 提交JSON)--> ComfyUI服务器 --(2. 处理生成)--> 图片 你的代码 <--(3. 获取图片)-- ComfyUI服务器现在你可能会问:“我怎么知道该发什么样的JSON过去?” 这就是接下来要解决的核心问题。
3. 准备工作:获取API所需的工作流定义
要调用API,你首先得知道ComfyUI当前加载的工作流长什么样。这个“长什么样”不是用眼睛看,而是要拿到它的JSON定义。
3.1 通过WebUI获取工作流JSON
最直接的方法就是从WebUI里导出。别担心,操作很简单:
- 打开你的Z-Image-GGUF WebUI界面(通常是
http://你的服务器IP:7860) - 确保已经加载了Z-Image工作流(注意:不要直接点默认工作流,要从左侧模板里选“加载Z-Image工作流”)
- 在WebUI的右上角,找到那个小小的“设置”齿轮图标,点击它
- 在弹出的菜单里,选择“导出工作流为JSON”
- 系统会下载一个JSON文件,用文本编辑器打开它
这个JSON文件就是整个工作流的“蓝图”,里面定义了所有节点、连接和参数。但直接用它还不行,我们需要稍微改造一下。
3.2 理解工作流JSON的结构
打开下载的JSON文件,你会看到类似这样的结构(我简化了一下,方便理解):
{ "last_node_id": 10, "last_link_id": 15, "nodes": [ { "id": 1, "type": "UnetLoaderGGUF", "widgets_values": ["z_image-Q4_K_M.gguf"] }, { "id": 3, "type": "CLIPTextEncode", "inputs": [["1", 0]], "widgets_values": ["a beautiful landscape", ""] }, { "id": 7, "type": "KSampler", "inputs": [["1", 0], ["3", 0], ["5", 0]], "widgets_values": [20, 5.0, "euler", "normal", 12345, 1] } ], "links": [ {"from_id": 3, "from_slot": 0, "to_id": 7, "to_slot": 1} ] }关键信息在这里:
nodes:所有节点的列表,每个节点有ID、类型和参数links:节点之间的连接关系widgets_values:节点的参数值,比如提示词、采样步数等
对于API调用,我们主要关心两件事:
- 哪些节点的参数需要动态改变(比如提示词)
- 整个工作流的执行顺序
4. 基础调用:你的第一个curl命令
理论讲得差不多了,现在咱们来点实际的。我先给你一个最基础的、能直接运行的示例,你感受一下整个过程有多简单。
4.1 完整的API调用示例
下面这个curl命令,就是调用Z-Image-GGUF生成一张樱花寺庙图片的完整代码:
curl -X POST http://localhost:7860/prompt \ -H "Content-Type: application/json" \ -d '{ "prompt": { "3": { "inputs": { "text": "a beautiful cherry blossom temple, sunset, cinematic lighting, 8k, masterpiece", "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "5": { "inputs": { "width": 1024, "height": 1024, "batch_size": 1 }, "class_type": "EmptyLatentImage" }, "7": { "inputs": { "seed": 12345, "steps": 20, "cfg": 5.0, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["1", 0], "positive": ["3", 0], "negative": ["4", 0], "latent_image": ["5", 0] }, "class_type": "KSampler" }, "8": { "inputs": { "samples": ["7", 0], "vae": ["2", 0] }, "class_type": "VAEDecode" }, "9": { "inputs": { "filename_prefix": "generated_image", "images": ["8", 0] }, "class_type": "SaveImage" } }, "client_id": "curl_client" }'让我解释一下这个命令的各个部分:
-X POST:告诉服务器我们要提交数据http://localhost:7860/prompt:API的地址,如果你的服务在别的机器上,把localhost换成对应的IP-H "Content-Type: application/json":声明我们发送的是JSON数据-d '...':后面跟着的就是我们要发送的JSON数据
4.2 理解JSON数据结构
JSON里面的prompt对象,其实就是我们之前看到的工作流定义,但做了一些调整:
- 节点用数字ID标识:比如
"3"对应CLIP文本编码节点 - 每个节点有两个关键属性:
class_type:节点类型,必须和ComfyUI里的类型名完全一致inputs:节点的输入参数,这里就是我们需要动态设置的地方
重点看看几个关键节点:
文本编码节点(ID: 3):
"3": { "inputs": { "text": "a beautiful cherry blossom temple...", # 这里放你的提示词 "clip": ["1", 0] # 连接到CLIP加载器 }, "class_type": "CLIPTextEncode" }潜在图像节点(ID: 5):
"5": { "inputs": { "width": 1024, # 图片宽度 "height": 1024, # 图片高度 "batch_size": 1 # 一次生成几张 }, "class_type": "EmptyLatentImage" }采样器节点(ID: 7):
"7": { "inputs": { "seed": 12345, # 随机种子,固定它可以让结果可复现 "steps": 20, # 采样步数,影响质量和速度 "cfg": 5.0, # 引导强度,越高越贴近提示词 "sampler_name": "euler", # 采样算法 "scheduler": "normal", # 调度器 "model": ["1", 0], # 连接到模型加载器 "positive": ["3", 0], # 连接到正向提示词 "latent_image": ["5", 0] # 连接到潜在图像 }, "class_type": "KSampler" }4.3 运行命令并查看结果
把上面的命令复制到终端里运行(记得确保ComfyUI服务已经启动),你会看到类似这样的响应:
{ "prompt_id": "f5a2b3c4d5e6", "node_errors": {}, "number": 1 }这个prompt_id很重要,它是你这次生成任务的唯一标识。图片生成需要时间,通常30-60秒,所以API不会立即返回图片,而是先返回一个任务ID。
那么问题来了:我怎么拿到生成的图片呢?
5. 获取生成结果:查询与下载图片
提交任务只是第一步,拿到图片才是我们的最终目的。ComfyUI提供了几种方式来获取生成结果。
5.1 方法一:通过历史记录API获取
最简单的方法是查询生成历史。等个几十秒(生成时间),然后运行:
# 获取历史记录列表 curl http://localhost:7860/history # 或者获取特定任务的历史 curl http://localhost:7860/history/f5a2b3c4d5e6你会得到一个包含所有生成信息的JSON响应。在输出里找到images部分,里面会有图片的文件名和子文件夹信息。
5.2 方法二:直接访问输出目录
ComfyUI会把生成的图片保存到服务器的文件系统里。默认情况下,Z-Image-GGUF的图片保存在:
/Z-Image-GGUF/output/你可以通过HTTP直接访问这些图片:
http://localhost:7860/output/generated_image_00001.png或者用curl下载到本地:
curl -O http://localhost:7860/output/generated_image_00001.png5.3 方法三:完整的自动化脚本
如果你想要一个完整的、从生成到下载的全自动流程,可以写一个简单的Shell脚本:
#!/bin/bash # 1. 提交生成任务 response=$(curl -s -X POST http://localhost:7860/prompt \ -H "Content-Type: application/json" \ -d '{ "prompt": { "3": { "inputs": {"text": "a beautiful landscape, mountains, lake, sunset", "clip": ["1", 0]}, "class_type": "CLIPTextEncode" }, "5": {"inputs": {"width": 1024, "height": 1024, "batch_size": 1}, "class_type": "EmptyLatentImage"}, "7": { "inputs": { "seed": 12345, "steps": 20, "cfg": 5.0, "sampler_name": "euler", "scheduler": "normal", "model": ["1", 0], "positive": ["3", 0], "negative": ["4", 0], "latent_image": ["5", 0] }, "class_type": "KSampler" }, "8": {"inputs": {"samples": ["7", 0], "vae": ["2", 0]}, "class_type": "VAEDecode"}, "9": {"inputs": {"filename_prefix": "auto_generated", "images": ["8", 0]}, "class_type": "SaveImage"} } }') # 2. 提取prompt_id prompt_id=$(echo $response | grep -o '"prompt_id":"[^"]*"' | cut -d'"' -f4) echo "任务ID: $prompt_id" # 3. 等待60秒(生成时间) echo "等待图片生成中..." sleep 60 # 4. 查询历史记录获取图片信息 history=$(curl -s http://localhost:7860/history/$prompt_id) # 5. 提取图片文件名(这里需要根据实际JSON结构调整) # 假设返回的JSON中图片信息在特定的路径,这里只是示例 filename=$(echo $history | grep -o '"filename":"[^"]*"' | head -1 | cut -d'"' -f4) # 6. 下载图片 if [ ! -z "$filename" ]; then echo "下载图片: $filename" curl -O http://localhost:7860/output/$filename else echo "未找到图片信息" fi这个脚本做了几件事:
- 提交生成任务并获取任务ID
- 等待足够的时间让图片生成完成
- 查询任务历史找到生成的图片文件名
- 下载图片到本地
6. 进阶技巧:参数调整与批量处理
现在你已经掌握了基础调用,接下来看看如何玩出更多花样。
6.1 动态修改生成参数
在实际使用中,你肯定不想每次都手动改JSON。我们可以用变量来动态构建请求:
#!/bin/bash # 定义变量 PROMPT_TEXT="a futuristic cityscape at night, neon lights, rain, cyberpunk style" IMAGE_WIDTH=768 IMAGE_HEIGHT=768 SAMPLING_STEPS=30 CFG_SCALE=7.5 SEED_VALUE=$RANDOM # 使用随机种子 # 构建JSON数据 JSON_DATA=$(cat <<EOF { "prompt": { "3": { "inputs": { "text": "$PROMPT_TEXT", "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "5": { "inputs": { "width": $IMAGE_WIDTH, "height": $IMAGE_HEIGHT, "batch_size": 1 }, "class_type": "EmptyLatentImage" }, "7": { "inputs": { "seed": $SEED_VALUE, "steps": $SAMPLING_STEPS, "cfg": $CFG_SCALE, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["1", 0], "positive": ["3", 0], "negative": ["4", 0], "latent_image": ["5", 0] }, "class_type": "KSampler" }, "8": { "inputs": { "samples": ["7", 0], "vae": ["2", 0] }, "class_type": "VAEDecode" }, "9": { "inputs": { "filename_prefix": "dynamic_gen", "images": ["8", 0] }, "class_type": "SaveImage" } } } EOF ) # 发送请求 curl -X POST http://localhost:7860/prompt \ -H "Content-Type: application/json" \ -d "$JSON_DATA"6.2 批量生成多张图片
想要一次生成多张不同主题的图片?用循环就行:
#!/bin/bash # 提示词列表 prompts=( "a serene mountain landscape with a clear lake, morning mist, photorealistic" "an ancient Chinese palace in snow, traditional architecture, detailed" "a cute cartoon cat wearing glasses and reading a book, anime style" "a sci-fi spaceship interior, neon lights, futuristic, cinematic" ) # 循环生成 for i in "${!prompts[@]}"; do echo "生成第 $((i+1)) 张图片: ${prompts[$i]}" JSON_DATA=$(cat <<EOF { "prompt": { "3": { "inputs": { "text": "${prompts[$i]}", "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "5": { "inputs": { "width": 1024, "height": 1024, "batch_size": 1 }, "class_type": "EmptyLatentImage" }, "7": { "inputs": { "seed": $((1000 + i)), "steps": 25, "cfg": 6.0, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["1", 0], "positive": ["3", 0], "negative": ["4", 0], "latent_image": ["5", 0] }, "class_type": "KSampler" }, "8": { "inputs": { "samples": ["7", 0], "vae": ["2", 0] }, "class_type": "VAEDecode" }, "9": { "inputs": { "filename_prefix": "batch_$((i+1))", "images": ["8", 0] }, "class_type": "SaveImage" } } } EOF ) # 提交任务 curl -s -X POST http://localhost:7860/prompt \ -H "Content-Type: application/json" \ -d "$JSON_DATA" > /dev/null echo "已提交,等待10秒后继续..." sleep 10 # 避免请求过于密集 done echo "所有任务已提交完成!"6.3 使用负向提示词
负向提示词告诉模型“不要生成什么”,对于提升图片质量很有帮助。在API调用中,我们需要添加一个负向提示词节点:
{ "prompt": { "3": { "inputs": { "text": "a beautiful portrait of a woman, professional photography, 8k", "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "4": { "inputs": { "text": "ugly, deformed, blurry, low quality, watermark, text", "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "7": { "inputs": { "seed": 12345, "steps": 20, "cfg": 5.0, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["1", 0], "positive": ["3", 0], # 连接到正向提示词 "negative": ["4", 0], # 连接到负向提示词 "latent_image": ["5", 0] }, "class_type": "KSampler" } } }注意看第7个节点(KSampler)的negative输入,现在连接到了节点4,也就是我们的负向提示词编码器。
7. 实战案例:构建一个简单的图片生成API服务
如果你想让其他程序也能调用这个图片生成功能,可以写一个简单的包装服务。下面我用Python写个示例,但原理用任何语言都一样。
7.1 Python Flask API示例
from flask import Flask, request, jsonify import requests import json import time import threading from queue import Queue import os app = Flask(__name__) # ComfyUI服务器地址 COMFYUI_URL = "http://localhost:7860" # 任务队列和结果存储 task_queue = Queue() results = {} def worker(): """后台工作线程,处理图片生成任务""" while True: task_id, prompt_data = task_queue.get() try: # 提交生成任务到ComfyUI response = requests.post( f"{COMFYUI_URL}/prompt", json={"prompt": prompt_data, "client_id": f"api_{task_id}"} ) if response.status_code == 200: result = response.json() prompt_id = result.get("prompt_id") # 等待生成完成(这里简化处理,实际应该轮询状态) time.sleep(45) # 获取历史记录找到图片 history_response = requests.get(f"{COMFYUI_URL}/history/{prompt_id}") if history_response.status_code == 200: history = history_response.json() # 这里需要根据实际返回结构解析图片信息 # 简化处理:假设第一个输出就是图片 results[task_id] = { "status": "completed", "message": "图片生成成功", "image_url": f"{COMFYUI_URL}/output/generated_image_00001.png" } else: results[task_id] = { "status": "error", "message": "无法获取生成历史" } else: results[task_id] = { "status": "error", "message": f"ComfyUI API错误: {response.status_code}" } except Exception as e: results[task_id] = { "status": "error", "message": f"处理错误: {str(e)}" } task_queue.task_done() # 启动工作线程 threading.Thread(target=worker, daemon=True).start() @app.route('/generate', methods=['POST']) def generate_image(): """生成图片的API端点""" data = request.json # 基础验证 if not data or 'prompt' not in data: return jsonify({"error": "需要提供prompt参数"}), 400 # 构建任务ID task_id = f"task_{int(time.time())}_{hash(str(data)) % 10000}" # 构建ComfyUI工作流数据 # 这里简化了,实际应该根据传入参数动态构建 comfyui_prompt = { "3": { "inputs": { "text": data['prompt'], "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "5": { "inputs": { "width": data.get('width', 1024), "height": data.get('height', 1024), "batch_size": 1 }, "class_type": "EmptyLatentImage" }, "7": { "inputs": { "seed": data.get('seed', 12345), "steps": data.get('steps', 20), "cfg": data.get('cfg', 5.0), "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["1", 0], "positive": ["3", 0], "negative": ["4", 0], "latent_image": ["5", 0] }, "class_type": "KSampler" }, "8": { "inputs": { "samples": ["7", 0], "vae": ["2", 0] }, "class_type": "VAEDecode" }, "9": { "inputs": { "filename_prefix": f"api_gen_{task_id}", "images": ["8", 0] }, "class_type": "SaveImage" } } # 添加负向提示词(如果提供了) if 'negative_prompt' in data: comfyui_prompt["4"] = { "inputs": { "text": data['negative_prompt'], "clip": ["1", 0] }, "class_type": "CLIPTextEncode" } # 将任务加入队列 task_queue.put((task_id, comfyui_prompt)) results[task_id] = {"status": "queued", "message": "任务已加入队列"} return jsonify({ "task_id": task_id, "status": "queued", "message": "图片生成任务已提交", "check_status_url": f"/status/{task_id}" }) @app.route('/status/<task_id>', methods=['GET']) def check_status(task_id): """检查任务状态""" if task_id not in results: return jsonify({"error": "任务不存在"}), 404 return jsonify(results[task_id]) @app.route('/list_tasks', methods=['GET']) def list_tasks(): """列出所有任务""" return jsonify({ "queued_tasks": task_queue.qsize(), "completed_tasks": {k: v for k, v in results.items() if v.get("status") == "completed"}, "all_tasks": list(results.keys()) }) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)这个简单的API服务提供了三个端点:
/generate:提交图片生成任务/status/<task_id>:检查任务状态/list_tasks:列出所有任务
现在你可以用curl测试这个服务:
# 提交生成任务 curl -X POST http://localhost:5000/generate \ -H "Content-Type: application/json" \ -d '{ "prompt": "a magical forest with glowing mushrooms, fantasy art, detailed", "width": 768, "height": 768, "steps": 30, "cfg": 7.0, "negative_prompt": "blurry, low quality, ugly" }' # 返回类似: # { # "task_id": "task_1700000000_1234", # "status": "queued", # "message": "图片生成任务已提交", # "check_status_url": "/status/task_1700000000_1234" # } # 检查任务状态 curl http://localhost:5000/status/task_1700000000_12347.2 更完整的参数支持
上面的示例比较基础,你可以扩展它来支持更多参数:
def build_comfyui_prompt(user_params): """根据用户参数构建ComfyUI工作流""" # 基础工作流模板 prompt = { "1": { "inputs": {"model_name": "z_image-Q4_K_M.gguf"}, "class_type": "UnetLoaderGGUF" }, "2": { "inputs": {"vae_name": "ae.safetensors"}, "class_type": "VAELoader" }, "3": { "inputs": { "text": user_params['prompt'], "clip": ["1", 0] }, "class_type": "CLIPTextEncode" }, "5": { "inputs": { "width": user_params.get('width', 1024), "height": user_params.get('height', 1024), "batch_size": user_params.get('batch_size', 1) }, "class_type": "EmptyLatentImage" }, "7": { "inputs": { "seed": user_params.get('seed', random.randint(1, 1000000)), "steps": user_params.get('steps', 20), "cfg": user_params.get('cfg', 5.0), "sampler_name": user_params.get('sampler', 'euler'), "scheduler": user_params.get('scheduler', 'normal'), "denoise": 1.0, "model": ["1", 0], "positive": ["3", 0], "negative": ["4", 0] if 'negative_prompt' in user_params else ["6", 0], "latent_image": ["5", 0] }, "class_type": "KSampler" }, "8": { "inputs": { "samples": ["7", 0], "vae": ["2", 0] }, "class_type": "VAEDecode" }, "9": { "inputs": { "filename_prefix": user_params.get('filename', 'generated'), "images": ["8", 0] }, "class_type": "SaveImage" } } # 添加负向提示词(如果提供) if 'negative_prompt' in user_params: prompt["4"] = { "inputs": { "text": user_params['negative_prompt'], "clip": ["1", 0] }, "class_type": "CLIPTextEncode" } else: # 默认的负向提示词 prompt["6"] = { "inputs": { "text": "low quality, blurry, ugly, bad anatomy", "clip": ["1", 0] }, "class_type": "CLIPTextEncode" } return prompt8. 错误处理与调试技巧
API调用难免会遇到问题,这里分享几个调试技巧。
8.1 常见错误及解决方法
错误1:连接被拒绝
curl: (7) Failed to connect to localhost port 7860: Connection refused原因:ComfyUI服务没有启动解决:检查服务状态并启动
supervisorctl status z-image-gguf supervisorctl start z-image-gguf错误2:无效的JSON响应
curl: (3) URL using bad/illegal format or missing URL原因:JSON格式错误或包含非法字符解决:使用jq验证JSON格式
echo '你的JSON数据' | jq .错误3:API返回错误信息
{ "error": { "message": "Invalid node id in link", "details": "..." } }原因:工作流JSON中的节点ID或连接有问题解决:从WebUI重新导出工作流,确保节点ID正确
8.2 调试命令和技巧
查看ComfyUI日志:
# 实时查看日志 tail -f /Z-Image-GGUF/z-image-gguf.log # 查看最近错误 grep -i error /Z-Image-GGUF/z-image-gguf.log | tail -20验证API端点:
# 检查API是否可用 curl http://localhost:7860/ # 查看可用端点 curl http://localhost:7860/object_info使用更详细的curl输出:
# 显示详细请求信息 curl -v -X POST http://localhost:7860/prompt \ -H "Content-Type: application/json" \ -d '{"prompt": {...}}' # 保存请求和响应到文件 curl -s -X POST http://localhost:7860/prompt \ -H "Content-Type: application/json" \ -d @request.json \ -o response.json8.3 使用Python进行更健壮的调用
如果你用Python,可以这样处理错误:
import requests import json import time def generate_image_with_retry(prompt_data, max_retries=3): """带重试的图片生成函数""" for attempt in range(max_retries): try: response = requests.post( "http://localhost:7860/prompt", json={"prompt": prompt_data}, timeout=120 # 120秒超时 ) response.raise_for_status() # 如果状态码不是200,抛出异常 result = response.json() if "error" in result: print(f"API返回错误: {result['error']}") if attempt < max_retries - 1: print(f"等待5秒后重试... (尝试 {attempt + 2}/{max_retries})") time.sleep(5) continue else: raise Exception(f"API错误: {result['error']}") return result except requests.exceptions.Timeout: print(f"请求超时 (尝试 {attempt + 1}/{max_retries})") if attempt < max_retries - 1: time.sleep(10) continue else: raise Exception("请求超时,已达到最大重试次数") except requests.exceptions.RequestException as e: print(f"网络错误: {e} (尝试 {attempt + 1}/{max_retries})") if attempt < max_retries - 1: time.sleep(5) continue else: raise raise Exception("所有重试都失败了") # 使用示例 try: result = generate_image_with_retry(your_prompt_data) print(f"任务提交成功,ID: {result.get('prompt_id')}") except Exception as e: print(f"生成失败: {e}")9. 总结
通过这篇文章,你应该已经掌握了用curl命令调用Z-Image-GGUF API生成图片的完整流程。让我们回顾一下关键点:
核心步骤:
- 获取工作流定义:从WebUI导出当前工作流的JSON结构
- 构建API请求:根据工作流JSON,构建包含动态参数的
prompt对象 - 提交生成任务:用
curl或编程语言发送POST请求到/prompt端点 - 获取任务ID:从响应中提取
prompt_id用于后续查询 - 查询生成结果:等待后通过
/history端点或直接访问输出目录获取图片
实用技巧:
- 使用变量和模板来动态构建JSON请求
- 通过循环实现批量图片生成
- 合理使用负向提示词提升图片质量
- 构建简单的API服务包装,方便其他程序调用
性能优化建议:
- 合理设置参数:根据需求平衡质量和速度(Steps: 20-30, CFG: 5-7)
- 使用队列系统:如果并发请求多,实现任务队列避免过载
- 缓存常用工作流:将工作流JSON保存为模板,避免每次重新构建
- 监控资源使用:定期检查GPU显存,避免内存不足
最后的小提示:
- 首次调用API时,模型需要加载到显存,可能会比较慢
- 图片生成时间通常在30-60秒,请合理设置超时时间
- 生成的图片默认保存在服务器的
/Z-Image-GGUF/output/目录 - 记得及时清理旧图片,避免磁盘空间不足
API调用的最大优势在于它的灵活性和可编程性。一旦你掌握了这个方法,就可以轻松地将AI图片生成能力集成到你的任何应用中,无论是自动化脚本、Web应用还是移动应用。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。