stable-diffusion-webui API开发指南:构建自动化AI图像生成服务

【免费下载链接】stable-diffusion-webui AUTOMATIC1111/stable-diffusion-webui - 一个为Stable Diffusion模型提供的Web界面,使用Gradio库实现,允许用户通过Web界面使用Stable Diffusion进行图像生成。 【免费下载链接】stable-diffusion-webui 项目地址: https://gitcode.com/GitHub_Trending/st/stable-diffusion-webui

1. 痛点与解决方案

你是否还在为手动调整Stable Diffusion参数而烦恼?是否需要将AI图像生成能力集成到自己的应用中?本文将详细介绍如何利用stable-diffusion-webui提供的API接口,构建自动化的AI图像生成服务,让你轻松实现文本到图像、图像到图像的批量处理,以及模型管理、任务监控等高级功能。

读完本文,你将能够:

  • 理解stable-diffusion-webui API的架构与核心端点
  • 掌握文本生成图像(Txt2Img)和图像生成图像(Img2Img)的API调用方法
  • 实现任务进度监控与批量图像处理
  • 管理模型、采样器、 upscale 等核心资源
  • 构建安全、高效的AI图像生成应用

2. API架构概览

stable-diffusion-webui的API系统基于FastAPI构建,提供了RESTful风格的接口,支持文本生成图像、图像生成图像、模型管理、任务监控等功能。API端点路径统一前缀为/sdapi/v1/,支持JSON格式的请求与响应。

2.1 API架构图

mermaid

2.2 核心API端点分类

类别 端点 功能描述
图像生成 /txt2img 文本生成图像
图像生成 /img2img 图像生成图像
图像处理 /extra-single-image 单图像增强(放大、修复)
图像处理 /extra-batch-images 批量图像增强
模型管理 /sd-models 获取/切换模型
模型管理 /refresh-checkpoints 刷新模型列表
系统配置 /options 获取/设置系统配置
系统状态 /progress 查询任务进度
资源管理 /samplers 获取采样器列表
资源管理 /upscalers 获取Upscaler列表

3. 环境准备与启动

3.1 安装与启动API服务

要启用API服务,需要在启动stable-diffusion-webui时添加--api参数:

# 克隆仓库
git clone https://gitcode.com/GitHub_Trending/st/stable-diffusion-webui.git
cd stable-diffusion-webui

# 启动WebUI并启用API
python launch.py --api --listen

3.2 启动参数说明

参数 说明
--api 启用API服务
--listen 允许局域网访问
--api-auth username:password 设置API访问认证
--api-log 启用API日志记录
--api-server-stop 启用服务停止/重启API

3.3 验证API服务

服务启动后,可以通过访问http://localhost:7860/sdapi/v1/health验证API是否正常运行,正常情况下会返回状态为200的响应。

4. 核心API使用指南

4.1 文本生成图像(Txt2Img)

4.1.1 请求格式

端点: /sdapi/v1/txt2img
方法: POST
内容类型: application/json

4.1.2 请求参数
参数 类型 默认值 说明
prompt string 生成图像的文本描述
negative_prompt string 不希望在图像中出现的内容
sampler_name string "Euler" 采样器名称
batch_size integer 1 每批生成图像数量
steps integer 20 采样步数
cfg_scale float 7.0 提示词相关性
width integer 512 图像宽度
height integer 512 图像高度
seed integer -1 随机种子,-1表示随机
send_images boolean true 是否返回图像数据
save_images boolean false 是否保存图像到本地
4.1.3 代码示例
import requests
import json
import base64
from PIL import Image
from io import BytesIO

# API端点
url = "http://localhost:7860/sdapi/v1/txt2img"

# 请求参数
payload = {
    "prompt": "a beautiful girl with blue eyes, wearing a red dress, in a garden, spring, high quality, detailed",
    "negative_prompt": "ugly, deformed, low quality, blurry",
    "sampler_name": "Euler a",
    "batch_size": 1,
    "n_iter": 1,
    "steps": 30,
    "cfg_scale": 7.5,
    "width": 512,
    "height": 768,
    "seed": 12345,
    "send_images": True,
    "save_images": False
}

# 发送请求
response = requests.post(url, json=payload)
data = response.json()

# 处理响应
if "images" in data and len(data["images"]) > 0:
    # 解码base64图像数据
    image_data = base64.b64decode(data["images"][0])
    image = Image.open(BytesIO(image_data))
    
    # 显示图像
    image.show()
    
    # 保存图像
    image.save("generated_image.png")
    
    # 打印生成信息
    print("生成参数:", data["parameters"])
    print("生成信息:", data["info"])
else:
    print("生成失败:", data)
4.1.4 响应格式
{
  "images": ["base64编码的图像数据..."],
  "parameters": {
    "prompt": "a beautiful girl...",
    "steps": 30,
    "seed": 12345,
    ...
  },
  "info": "{\"prompt\": \"a beautiful girl...\", \"seed\": 12345, ...}"
}

4.2 图像生成图像(Img2Img)

4.2.1 请求格式

端点: /sdapi/v1/img2img
方法: POST
内容类型: application/json

4.2.2 关键参数
参数 类型 默认值 说明
init_images array [] 初始图像(base64编码)
mask string null 遮罩图像(base64编码)
prompt string 生成图像的文本描述
denoising_strength float 0.75 去噪强度(0-1),值越高创造性越强
resize_mode integer 0 调整大小模式(0:调整到指定尺寸,1:保持比例裁剪)
4.2.3 代码示例
import requests
import base64
from PIL import Image
from io import BytesIO

# 读取图像并转换为base64
def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# API端点
url = "http://localhost:7860/sdapi/v1/img2img"

# 图像路径
image_path = "input_image.png"
mask_path = "mask.png"  # 可选

# 转换为base64
image_base64 = image_to_base64(image_path)
mask_base64 = image_to_base64(mask_path) if mask_path else None

# 请求参数
payload = {
    "init_images": [image_base64],
    "mask": mask_base64,
    "prompt": "a beautiful girl with blue eyes, wearing a red dress, in a garden, spring, high quality, detailed",
    "negative_prompt": "ugly, deformed, low quality, blurry",
    "sampler_name": "Euler a",
    "denoising_strength": 0.6,
    "batch_size": 1,
    "n_iter": 1,
    "steps": 30,
    "cfg_scale": 7.5,
    "width": 512,
    "height": 768,
    "seed": 12345,
    "send_images": True,
    "save_images": False,
    "include_init_images": False
}

# 发送请求
response = requests.post(url, json=payload)
data = response.json()

# 处理响应
if "images" in data and len(data["images"]) > 0:
    image_data = base64.b64decode(data["images"][0])
    image = Image.open(BytesIO(image_data))
    image.save("img2img_result.png")
    image.show()

4.3 任务进度监控

在处理大型图像或批量生成时,需要实时监控任务进度。

4.3.1 进度查询API

端点: /sdapi/v1/progress
方法: GET

4.3.2 响应格式
{
  "progress": 0.75,  // 进度(0-1)
  "eta_relative": 10.5,  // 预计剩余时间(秒)
  "state": {
    "job": "txt2img",  // 当前任务类型
    "job_count": 1,  // 任务总数
    "job_no": 1,  // 当前任务序号
    "sampling_step": 22,  // 当前采样步数
    "sampling_steps": 30  // 总采样步数
  },
  "current_image": "base64编码的当前图像...",  // 当前生成的图像(可选)
  "textinfo": "采样步骤: 22/30"  // 文本信息
}
4.3.3 进度监控代码示例
import requests
import time

def monitor_progress(url, interval=1):
    """监控任务进度,直到完成或失败"""
    while True:
        response = requests.get(f"{url}/sdapi/v1/progress")
        data = response.json()
        
        progress = data.get("progress", 0)
        eta = data.get("eta_relative", 0)
        state = data.get("state", {})
        
        print(f"进度: {progress*100:.2f}% | 预计剩余: {eta:.1f}秒 | 步骤: {state.get('sampling_step', 0)}/{state.get('sampling_steps', 0)}")
        
        if progress >= 1.0:
            print("任务完成!")
            break
            
        time.sleep(interval)

# 使用示例
monitor_progress("http://localhost:7860", interval=1)

5. 高级功能

5.1 模型管理

stable-diffusion-webui API提供了完整的模型管理功能,可以查询、切换模型,以及刷新模型列表。

5.1.1 获取模型列表

端点: /sdapi/v1/sd-models
方法: GET

响应示例:

[
  {
    "title": "v1-5-pruned-emaonly.safetensors [cc6cb27103]",
    "model_name": "v1-5-pruned-emaonly.safetensors",
    "hash": "cc6cb27103",
    "sha256": "cc6cb27103...",
    "filename": "/path/to/models/Stable-diffusion/v1-5-pruned-emaonly.safetensors",
    "config": "/path/to/configs/v1-inference.yaml"
  },
  ...
]
5.1.2 切换模型

要切换模型,需要通过/options端点设置sd_model_checkpoint参数:

import requests

url = "http://localhost:7860/sdapi/v1/options"

# 获取当前配置
current_options = requests.get(url).json()

# 设置新模型
model_name = "v1-5-pruned-emaonly.safetensors [cc6cb27103]"
response = requests.post(url, json={"sd_model_checkpoint": model_name})

if response.status_code == 200:
    print(f"成功切换模型为: {model_name}")
else:
    print(f"切换模型失败: {response.text}")

5.2 系统配置管理

API允许获取和修改系统配置,包括图像保存路径、采样器默认参数、UI设置等。

5.2.1 获取系统配置

端点: /sdapi/v1/options
方法: GET

响应包含大量配置参数,涵盖系统各方面设置。

5.2.2 修改系统配置

端点: /sdapi/v1/options
方法: POST
请求体: 要修改的配置参数键值对

示例: 修改图像保存路径和默认采样步数

import requests

url = "http://localhost:7860/sdapi/v1/options"

# 配置参数
config = {
    "outdir_txt2img_samples": "/path/to/custom/txt2img",
    "outdir_img2img_samples": "/path/to/custom/img2img",
    "steps": 30  # 默认采样步数
}

response = requests.post(url, json=config)

if response.status_code == 200:
    print("配置修改成功")
else:
    print(f"配置修改失败: {response.text}")

5.3 批量图像处理

API提供了批量图像处理功能,可以同时对多张图像进行放大、修复等操作。

5.3.1 批量图像增强

端点: /sdapi/v1/extra-batch-images
方法: POST

请求示例:

{
  "imageList": [
    {"data": "base64编码的图像1...", "name": "image1.png"},
    {"data": "base64编码的图像2...", "name": "image2.png"}
  ],
  "resize_mode": 0,
  "upscaling_resize": 2,
  "upscaler_1": "R-ESRGAN 4x+",
  "gfpgan_visibility": 0.5,
  "codeformer_visibility": 0
}

6. 安全与性能优化

6.1 API认证

为保护API安全,可以启用基本认证:

# 启动时设置认证
python launch.py --api --api-auth username:password

认证请求示例:

import requests
from requests.auth import HTTPBasicAuth

url = "http://localhost:7860/sdapi/v1/txt2img"
payload = {"prompt": "a beautiful girl", "steps": 20}

# 添加认证信息
response = requests.post(
    url, 
    json=payload,
    auth=HTTPBasicAuth("username", "password")
)

6.2 请求限流与队列管理

stable-diffusion-webui API内部实现了请求队列管理,多个请求会按顺序处理。可以通过以下参数调整队列行为:

参数 说明
--api-queue-timeout API请求超时时间(秒)
--max-batch-count 最大批处理数量

6.3 性能优化策略

  1. 调整批量大小: 根据GPU内存,合理设置batch_sizen_iter参数
  2. 降低分辨率: 生成低分辨率图像,再通过Upscaler放大
  3. 减少采样步数: 在可接受质量范围内减少steps参数
  4. 使用高效采样器: 如Euler a、LMS等速度较快的采样器
  5. 模型优化: 使用fp16精度模型,启用xFormers优化
# 优化的生成参数示例
payload = {
    "prompt": "a beautiful girl",
    "sampler_name": "Euler a",  # 高效采样器
    "steps": 20,  # 减少采样步数
    "batch_size": 2,  # 适当批量大小
    "width": 512,
    "height": 512,
    "enable_hr": True,  # 启用高清修复
    "hr_scale": 2,  # 放大2倍
    "hr_second_pass_steps": 10,  # 高清修复步数
    "hr_resize_x": 1024,
    "hr_resize_y": 1024
}

7. 实际应用案例

7.1 构建自动图像生成服务

以下是一个完整的自动图像生成服务示例,包括任务提交、进度监控、结果处理:

import requests
import time
import base64
import json
from PIL import Image
from io import BytesIO
from dataclasses import dataclass
from typing import List, Optional, Dict

@dataclass
class ImageGenerationRequest:
    prompt: str
    negative_prompt: str = ""
    width: int = 512
    height: int = 512
    steps: int = 20
    sampler_name: str = "Euler a"
    cfg_scale: float = 7.5
    seed: int = -1
    batch_size: int = 1

@dataclass
class ImageGenerationResult:
    images: List[Image.Image]
    parameters: Dict
    info: str
    seed: int

class StableDiffusionAPIClient:
    def __init__(self, base_url: str, username: Optional[str] = None, password: Optional[str] = None):
        self.base_url = base_url
        self.auth = (username, password) if username and password else None
        
    def generate_image(self, request: ImageGenerationRequest) -> ImageGenerationResult:
        """生成图像并返回结果"""
        # 提交生成任务
        url = f"{self.base_url}/sdapi/v1/txt2img"
        payload = request.__dict__
        payload["send_images"] = True
        payload["save_images"] = False
        
        response = requests.post(url, json=payload, auth=self.auth if self.auth else None)
        response.raise_for_status()
        data = response.json()
        
        # 解码图像
        images = []
        for img_data in data["images"]:
            image = Image.open(BytesIO(base64.b64decode(img_data)))
            images.append(image)
            
        # 解析信息
        info = json.loads(data["info"])
        seed = info.get("seed", request.seed)
        
        return ImageGenerationResult(
            images=images,
            parameters=data["parameters"],
            info=data["info"],
            seed=seed
        )
        
    def monitor_progress(self, interval: float = 1.0) -> None:
        """监控当前任务进度"""
        url = f"{self.base_url}/sdapi/v1/progress"
        
        while True:
            response = requests.get(url, auth=self.auth if self.auth else None)
            response.raise_for_status()
            data = response.json()
            
            progress = data.get("progress", 0)
            eta = data.get("eta_relative", 0)
            state = data.get("state", {})
            
            print(f"进度: {progress*100:.1f}% | 剩余时间: {eta:.1f}s | 步骤: {state.get('sampling_step', 0)}/{state.get('sampling_steps', 0)}")
            
            if progress >= 1.0:
                print("生成完成!")
                break
                
            time.sleep(interval)

# 使用示例
if __name__ == "__main__":
    # 创建客户端
    client = StableDiffusionAPIClient(
        base_url="http://localhost:7860",
        # username="your_username",
        # password="your_password"
    )
    
    # 创建请求
    request = ImageGenerationRequest(
        prompt="a beautiful girl with blue eyes, wearing a red dress, in a garden, spring, high quality, detailed",
        negative_prompt="ugly, deformed, low quality, blurry",
        steps=30,
        width=512,
        height=768,
        batch_size=2
    )
    
    # 提交任务并监控进度
    print("开始生成图像...")
    import threading
    progress_thread = threading.Thread(target=client.monitor_progress, args=(1.0,))
    progress_thread.start()
    
    # 生成图像
    result = client.generate_image(request)
    
    # 等待进度线程结束
    progress_thread.join()
    
    # 保存结果
    for i, image in enumerate(result.images):
        image.save(f"generated_image_{i}_{result.seed}.png")
        print(f"保存图像: generated_image_{i}_{result.seed}.png")

7.2 集成到Web应用

可以将API集成到Web应用中,提供在线AI图像生成服务。以下是一个简单的Flask应用示例:

from flask import Flask, request, jsonify, send_file
import requests
import base64
from io import BytesIO
from PIL import Image
import uuid
import os

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = "uploads"
app.config["GENERATED_FOLDER"] = "generated"

# 确保目录存在
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
os.makedirs(app.config["GENERATED_FOLDER"], exist_ok=True)

# Stable Diffusion API客户端
SD_API_URL = "http://localhost:7860"
SD_API_USERNAME = ""  # API用户名
SD_API_PASSWORD = ""  # API密码

@app.route("/api/generate", methods=["POST"])
def generate():
    """处理图像生成请求"""
    data = request.json
    
    # 验证请求参数
    if not data or "prompt" not in data:
        return jsonify({"error": "缺少prompt参数"}), 400
    
    # 构建SD API请求
    payload = {
        "prompt": data["prompt"],
        "negative_prompt": data.get("negative_prompt", ""),
        "steps": data.get("steps", 20),
        "width": data.get("width", 512),
        "height": data.get("height", 512),
        "sampler_name": data.get("sampler", "Euler a"),
        "cfg_scale": data.get("cfg_scale", 7.5),
        "seed": data.get("seed", -1),
        "batch_size": data.get("batch_size", 1),
        "send_images": True,
        "save_images": False
    }
    
    # 发送请求到SD API
    try:
        response = requests.post(
            f"{SD_API_URL}/sdapi/v1/txt2img",
            json=payload,
            auth=(SD_API_USERNAME, SD_API_PASSWORD) if SD_API_USERNAME and SD_API_PASSWORD else None
        )
        response.raise_for_status()
        result = response.json()
        
        # 处理结果
        if not result.get("images"):
            return jsonify({"error": "生成失败,未返回图像"}), 500
            
        # 保存图像并返回URL
        image_data = base64.b64decode(result["images"][0])
        image_filename = f"{uuid.uuid4()}.png"
        image_path = os.path.join(app.config["GENERATED_FOLDER"], image_filename)
        
        with open(image_path, "wb") as f:
            f.write(image_data)
            
        return jsonify({
            "success": True,
            "image_url": f"/generated/{image_filename}",
            "seed": json.loads(result["info"]).get("seed", payload["seed"]),
            "parameters": result["parameters"]
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/generated/<filename>")
def get_generated_image(filename):
    """提供生成的图像下载"""
    return send_file(os.path.join(app.config["GENERATED_FOLDER"], filename))

if __name__ == "__main__":
    app.run(debug=True, port=5000)

8. 常见问题与解决方案

8.1 API调用失败

问题 可能原因 解决方案
401 Unauthorized 认证失败 检查用户名密码是否正确
404 Not Found 端点不存在 确认API路径是否正确,服务是否启用
500 Internal Server Error 服务器内部错误 查看WebUI控制台日志,检查请求参数是否正确
连接超时 服务未启动或网络问题 确认WebUI已启动并启用API,检查网络连接

8.2 生成质量问题

问题 可能原因 解决方案
图像模糊 分辨率低或采样步数少 提高分辨率,增加采样步数
图像不符合预期 提示词不明确 优化提示词,添加更多细节描述
生成速度慢 参数设置不合理 减少分辨率、采样步数,使用更快的采样器
显存不足 批量过大或分辨率过高 减小批量大小,降低分辨率,启用低显存模式

8.3 性能优化建议

  1. 启用xFormers: 添加--xformers启动参数,显著减少显存占用
  2. 使用fp16模型: 加载模型时选择fp16版本,减少显存使用
  3. 启用模型缓存: 添加--no-half-vae参数,避免重复加载模型
  4. 调整线程数: 使用--api-thread-count参数设置API线程数

9. 总结与展望

stable-diffusion-webui API提供了强大的图像生成与管理能力,通过本文介绍的方法,你可以轻松构建自动化的AI图像生成服务。无论是批量处理、应用集成还是二次开发,API都提供了灵活、高效的接口。

随着stable-diffusion-webui的不断更新,API功能也在持续增强。未来可能会添加更多高级功能,如模型训练API、扩展管理API等,为开发者提供更全面的AI图像生成工具链。

9.1 关键知识点回顾

  • API架构: 基于FastAPI构建,RESTful风格接口
  • 核心功能: 文本生成图像、图像生成图像、图像处理、模型管理
  • 高级应用: 任务监控、批量处理、应用集成
  • 性能优化: 参数调优、模型选择、硬件加速

9.2 后续学习路径

  1. 深入学习提示词工程(Prompt Engineering),优化生成效果
  2. 探索扩展API功能,开发自定义扩展
  3. 研究模型训练API,构建自定义模型训练流程
  4. 学习分布式部署,构建高可用的AI图像生成服务

10. 参考资源

  • stable-diffusion-webui官方文档: https://github.com/AUTOMATIC1111/stable-diffusion-webui
  • FastAPI官方文档: https://fastapi.tiangolo.com/
  • Stable Diffusion模型库: https://civitai.com/
  • 提示词工程指南: https://github.com/dair-ai/Prompt-Engineering-Guide

希望本文能帮助你快速掌握stable-diffusion-webui API的使用,构建强大的AI图像生成应用。如有任何问题或建议,欢迎在评论区留言讨论。

如果你觉得本文有帮助,请点赞、收藏、关注,获取更多AI开发技巧!

下期预告: Stable Diffusion模型训练API实战指南

【免费下载链接】stable-diffusion-webui AUTOMATIC1111/stable-diffusion-webui - 一个为Stable Diffusion模型提供的Web界面,使用Gradio库实现,允许用户通过Web界面使用Stable Diffusion进行图像生成。 【免费下载链接】stable-diffusion-webui 项目地址: https://gitcode.com/GitHub_Trending/st/stable-diffusion-webui

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐