stable diffusion api 文生图
时间: 2025-01-23 18:10:28 浏览: 77
### 使用 Stable Diffusion API 实现文本到图像生成功能
为了实现从文本生成图像的功能,`stable-diffusion-api-server` 提供了一个本地API服务器接口来访问Stable Diffusion模型[^1]。该服务允许开发者通过HTTP请求提交文本描述,并接收由模型生成的对应图像作为响应。
下面是一个简单的Python脚本示例,展示了如何调用此API来进行文本转图像的操作:
```python
import requests
from PIL import Image
from io import BytesIO
def generate_image_from_text(prompt, api_url='http://localhost:8080'):
"""
发送POST请求给稳定扩散API以创建新图象
参数:
prompt (str): 文字提示语句.
api_url (str): API端点URL,默认为'http://localhost:8080'.
返回:
img (PIL.Image.Image): 生成的图片对象.
"""
response = requests.post(
f'{api_url}/sdapi/v1/txt2img',
json={
"prompt": prompt,
"steps": 50,
"width": 768,
"height": 768,
"n_iter": 1,
"batch_size": 1
}
)
if response.status_code == 200:
image_data = BytesIO(response.content)
img = Image.open(image_data)
return img
else:
raise Exception(f'Error generating image: {response.text}')
# 测试函数
if __name__ == '__main__':
try:
generated_img = generate_image_from_text('a beautiful sunset over mountains')
generated_img.show()
except Exception as e:
print(e)
```
这段代码定义了一个名为 `generate_image_from_text()` 的函数,它可以接受一段文字描述作为参数,并向指定的API发送一个JSON格式的数据包。如果一切顺利的话,将会返回一张根据所给定的文字描述而合成的新图片。
需要注意的是,实际部署环境中可能需要调整API URL以及配置其他必要的参数(比如认证令牌)。此外,对于更复杂的场景,还可以探索更多高级选项,例如设置不同的采样步数(`steps`)、宽度和高度等属性来自定义最终输出的质量与风格[^3]。
阅读全文
相关推荐


















