python --读取psd文件

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)
相关推荐
阿尔的代码屋4 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
CoovallyAIHub1 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉