import requests
import base64
import os
from PIL import Image
import io
import json
import random
# 用于将图片编码为Base64格式的函数
def encode_pil_to_base64(image):
with io.BytesIO() as output_bytes:
image.save(output_bytes, format="PNG") # 注意PNG格式
bytes_data = output_bytes.getvalue()
return base64.b64encode(bytes_data).decode("utf-8")
# 生成LoRA模型信息字符串的函数
def joinLoraList(loraPath, weight):
# LoRA路径编码为Base64以便嵌入到提示词中
loraPathEncoded = base64.b64encode(loraPath.encode("utf-8")).decode("utf-8")
return f"<lora:{loraPathEncoded}:{weight:.1f}>"
# 主程序
def main():
# API的URL
url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
# 指定LoRA模型路径和权重
loraModelPath = r"C:\AI\models\Lora\CWG_archisketch_v1.safetensors"
weight = 1.0
# 生成LoRA模型信息字符串
loraInfo = joinLoraList(loraModelPath, weight)
# 定制的提示词
customPrompt = "Building, masterpiece, best quality, pre sketch,"
# 将LoRA信息放在提示词前面
prompt = loraInfo + " " + customPrompt
# 获取参考图片,并编码为Base64
reference_image_dir = r"C:\Users\wujie1\Desktop\图片参考素材"
latest_file_path = max([os.path.join(reference_image_dir, f) for f in os.listdir(reference_image_dir) if os.path.isfile(os.path.join(reference_image_dir, f))], key=os.path.getctime)
with Image.open(latest_file_path) as img:
encoded_image = encode_pil_to_base64(img)
# 读取最新图片的长宽
img_width, img_height = img.size
# 构建请求的payload
data = {
"prompt": "<lora:CWG_archisketch_v1:1>,Building,masterpiece,best quality,pre sketch,",
"negative_prompt": "blurry, lower , 3D",
"sampler_name": "DPM++ 2M Karras",
"init_image": encoded_image,
"steps": 25,
# 设置图片宽高为最新图片的宽高
"width": img_width,
"height": img_height,
"seed": random.randint(1, 10000000),
}
# 发送请求并获取响应
response = requests.post(url, json=data)
response_json = response.json()
# 定义图像保存的路径并保存图像
save_path = r"C:\Users\wujie1\Downloads\Generated_Image.png"
with open(save_path, 'wb') as f:
f.write(base64.b64decode(response_json['images'][0]))
print(f"图片已保存到: {save_path}")
if __name__ == '__main__':
main()