ai_service/scripts/export_psd.py
2025-05-20 17:01:40 +08:00

91 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# export_psd.py - PSD导出 (适配psd-tools 1.10.0 API)
import os
from PIL import Image
import logging
# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 设置默认目录路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEFAULT_INPUT_DIR = os.path.join(project_root, 'images')
DEFAULT_OUTPUT_DIR = os.path.join(project_root, 'outputs')
def export_to_psd(layers, output_path, layer_names=None, canvas_size=(1080, 1920)):
# 先导入compose_poster中的函数
from compose_poster import compose_layers
try:
# 导入psd-tools相关模块
from psd_tools import PSDImage
from psd_tools.api.layers import PixelLayer
from psd_tools.constants import Compression
except ImportError:
logger.error("未安装psd-tools库无法导出PSD。请安装pip install psd-tools>=1.10.0")
return ""
logger.info(f"开始创建PSD文件包含{len(layers)}个图层...")
# 1. 先使用compose_layers合成图层
temp_output = os.path.join(DEFAULT_OUTPUT_DIR, "temp_composed.png")
composed_path = compose_layers(layers, temp_output, canvas_size)
if not composed_path:
logger.error("图层合成失败")
return ""
# 2. 处理输出路径
if not os.path.isabs(output_path):
output_path = os.path.join(DEFAULT_OUTPUT_DIR, output_path)
if not output_path.lower().endswith('.psd'):
output_path += '.psd'
# 确保输出目录存在
output_dir = os.path.dirname(output_path)
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir)
try:
# 3. 创建PSD文件
psd = PSDImage.new('RGB', canvas_size)
# 4. 添加合成后的图层
composed_image = Image.open(composed_path).convert('RGBA')
pixel_layer = PixelLayer.frompil(composed_image, psd, "Composed_Layer")
psd.append(pixel_layer)
# 5. 保存PSD文件
psd.save(output_path)
logger.info(f"PSD文件已成功创建并保存到: {output_path}")
# 6. 清理临时文件
if os.path.exists(temp_output):
os.remove(temp_output)
return output_path
except Exception as e:
logger.error(f"创建PSD文件时出错: {str(e)}")
logger.exception(e)
return ""
if __name__ == "__main__":
# 简单测试
from sys import argv
if len(argv) >= 3:
# 从命令行接收参数
layers = argv[1:-1]
output = argv[-1]
result = export_to_psd(layers, output)
if result:
print(f"PSD文件已成功导出到: {result}")
else:
print("PSD文件导出失败")
else:
print("用法: python export_psd.py layer1.png layer2.png ... output.psd")
print(f"默认输入目录: {DEFAULT_INPUT_DIR}")
print(f"默认输出目录: {DEFAULT_OUTPUT_DIR}")
print("注意:如果只提供文件名,将从默认输入目录查找图片文件")