Python 调用 Stabilityai API在本地生成图像
Python 调用 Stabilityai API在本地生成图像
- 摘要
- 功能
- 代码结构
- 关键技术
- 代码下载
- 立即体验
摘要
本程序利用硅基流动目前的免费 stabilityai/stable-diffusion-2-1 模型API,生成图像并下载到本地,用户可以通过输入描述性提示词来获取相应的图像。使用Python编写,依赖于requests库进行HTTP请求,并使用os库处理文件系统操作。
功能
- 用户输入:程序提示用户输入描述图像的提示词,例如:‘an island near sea, with seagulls, moon
shining over the sea, light house, boats int he background, fish
flying over the sea’。输入提示词时,不要少了前后的单引号哦。 - API请求:使用用户输入的提示词构建请求负载,并向指定的API发送POST请求以生成图像。(代码中有)
- 响应处理:解析API的响应,提取生成的图像URL。
- 文件保存:将生成的图像下载并保存到本地文件系统,文件名基于用户输入的前10个字符命名。
- 目录管理:在保存图像之前,检查并创建必要的目录。
代码结构
代码结构
以下是应用程序的主要代码结构:
# -*- coding: utf-8 -*-
import requests
import osurl = "https://api.siliconflow.cn/v1/images/generations"# 提示用户输入描述图片的提示词
try:user_input = input("\n请输入描述图片的提示词,例如:'blue sky': ").strip() # 用户输入需要引号user_prompt = "'{}'".format(user_input)
except Exception as e:print("输入提示词时发生错误: {}".format(e))exit(1) # 退出程序payload = {"model": "deepseek-ai/Janus-Pro-7B","prompt": user_prompt, # 使用用户输入的提示词"seed": 4999999999
}
headers = {"Authorization": "Bearer <token>", #<token> 替换成你在硅基流动里的 API-KEY, 文末有如何获得。"Content-Type": "application/json"
}response = requests.request("POST", url, json=payload, headers=headers)# 解析响应以获取图像URL
response_json = response.json() # 使用 json() 方法解析响应
image_url = response_json['data'][0]['url'] # 从 data 数组中获取 URL# 定义保存图像的本地文件名
local_filename = os.path.join("images", "{}.png".format(user_input[:10])) # 使用用户输入的前10个字符命名# 创建图像目录(如果不存在)
if not os.path.exists(os.path.dirname(local_filename)):os.makedirs(os.path.dirname(local_filename))# 下载图像并保存到本地
with requests.get(image_url, stream=True) as img_response:img_response.raise_for_status() # 检查请求错误with open(local_filename, 'wb') as f:for chunk in img_response.iter_content(chunk_size=8192):f.write(chunk)print("Image saved to {local_filename}")
关键技术
HTTP请求:使用requests库简化HTTP请求的发送和响应处理。
JSON解析:通过response.json()方法轻松解析API返回的JSON数据。
文件操作:使用os库处理文件路径和目录创建,确保图像能够正确保存。
总结
本应用程序展示了如何通过API生成图像,并将其保存到本地。用户友好的输入提示和自动化的文件管理使得该应用程序易于使用,适合需要快速生成图像的场景。
代码下载
https://gitee.com/phpervip/py-stability-ai/
立即体验
现在就开始吧!
https://cloud.siliconflow.cn/i/7qQzHGZs
https://cloud.siliconflow.cn/i/7qQzHGZs
https://cloud.siliconflow.cn/i/7qQzHGZs