python
复制代码
# py3.7.3 psd-tools==1.9.28
from psd_tools import PSDImage
from PIL import Image
import os
def read_and_show_psd(psd_path: str, show_layer: bool = False):
"""
读取 PSD 文件并显示图片(适配你提供的 PSDImage 源码版本)
:param psd_path: PSD 文件路径
:param show_layer: 是否显示第一个图层(False 显示合并后的完整图像)
"""
# 1. 检查文件是否存在
if not os.path.exists(psd_path):
print(f"错误:文件 {psd_path} 不存在!")
return
# 2. 读取 PSD 文件(用源码指定的 PSDImage.open 方法)
try:
psd = PSDImage.open(psd_path)
print(f"成功读取 PSD:{psd_path}")
print(f"PSD 尺寸:{psd.size}(宽x高)")
# 读取图层(用源码的 _layers 属性,或直接遍历 psd)
layer_count = len(psd._layers) # 源码里图层存在 _layers 中
print(f"图层数量:{layer_count}")
except Exception as e:
print(f"读取 PSD 失败:{e}")
return
# 3. 显示图像(核心用 composite() 方法,源码明确支持)
# 方式1:显示合并后的完整图像(推荐,最稳定)
if not show_layer:
# 合成完整图像(源码的 composite 方法)
img = psd.composite()
if img is not None:
img.show() # 调用系统图片查看器显示
# 可选:保存为 PNG
# img.save("psd_merged.png")
else:
print("错误:无法合成完整图像!")
# 方式2:显示第一个图层
else:
if len(psd._layers) > 0:
# 取第一个图层,合成图层图像
first_layer = psd._layers[2]
layer_img = first_layer.composite() # 图层也有 composite 方法
if layer_img is not None:
print(f"显示图层:{first_layer.name if hasattr(first_layer, 'name') else '未命名图层'}")
layer_img.show()
else:
print("错误:无法合成该图层!")
else:
print("PSD 无图层!")
# ===================== 测试调用 =====================
if __name__ == "__main__":
# 替换为你的 PSD 文件路径(建议用绝对路径,避免中文/空格)
psd_file_path = r"C:\Users\123\Desktop\12.psd" # 示例:D:/project/test.psd
# 显示合并后的完整图像
# read_and_show_psd(psd_file_path)
# 如需显示第一个图层,传入 show_layer=True
read_and_show_psd(psd_file_path, show_layer=True)