如何在 Python 中检查 PSD 文档部分

如何在 Python 中检查 PSD 文档部分

已加载的 PsdImage 会公开只读的摘要对象,用于 PSD/PSB 文档的结构化部分——标题、颜色数据段、图像数据段和图像资源段——且无需手动进行字节级解析。

分步指南

步骤 1:安装软件包

git clone https://github.com/aspose-psd-foss/Aspose.PSD-FOSS-for-Python.git
cd Aspose.PSD-FOSS-for-Python
# No packaging manifest is published yet -- run from this folder,
# or add it to PYTHONPATH:
export PYTHONPATH=$PWD:$PYTHONPATH

步骤 2:导入所需类

from aspose_psd_foss.psdimage import PsdImage

步骤 3:检查标题部分

PsdImage.header 返回一个 PsdHeader,其中包含文档的原始结构字段:

image = PsdImage.load("input.psd")

header = image.header
print(f"Size: {header.width}x{header.height}, channels: {header.channels}")
print(f"Bit depth: {header.bit_depth}, raw color mode: {header.color_mode}")
print(f"Is PSB: {header.is_large_document}")

PsdHeader.color_mode 返回文件中存储的原始整数颜色模式字段——如果需要强类型的 ColorModes 枚举,请改用 PsdImage.color_mode。


步骤 4:检查颜色数据段

PsdImage.color_data_info 返回一个 PsdColorDataInfo 摘要;kind 是一个 PsdColorDataKind 值(NONE、INDEXED_PALETTE、RGB_PAYLOAD、CMYK_PAYLOAD 或 RAW_PRESERVED):

if image.has_color_mode_data:
    color_info = image.color_data_info
    print(f"Color data kind: {color_info.kind}, raw bytes: {color_info.raw_data_length}")

    if color_info.indexed_palette is not None:
        print(f"Indexed palette entries: {len(color_info.indexed_palette.entries)}")

步骤 5:检查图像数据段

PsdImage.image_data_info 返回一个 PsdImageDataInfo 摘要,描述合并像素数据的编码方式:

data_info = image.image_data_info
print(f"Compression: {image.compression}")
print(f"Data kind: {data_info.kind}, uses prediction: {data_info.uses_prediction}")
print(f"Compressed payload length: {data_info.compressed_payload_length}")

data_info.kind 是一个 ImageDataKind 值(RAW、RLE、ZIP 或 UNKNOWN),描述合并图像数据自身的编码——image.compression 通过单独的 CompressionMethod 枚举报告相同的编码。


步骤 6:检查图像资源段

print(f"Has image resources: {image.has_image_resources}")
print(f"Resource count: {image.resource_count}")

for resource in image.resources:
    print(f"Resource ID: {resource.resource_id}, kind: {resource.kind}")

PsdImage.resources 返回只读 PsdResourceInfo 摘要。单独的 PsdImage.image_resources 属性也有 getter,但其 setter 会抛出 NotSupportedException 在此 FOSS 构建中 — 请参见 Troubleshooting 查看完整的只读 setter 列表。

常见问题与解决方案

header.color_mode 不匹配 image.color_mode. 这是预期的 — PsdHeader.color_mode 是来自文件的原始整数字段,而 PsdImage.color_mode 是强类型的 ColorModes 由它构建的枚举。

color_data_info.indexed_palette is None. 文档的颜色数据类型不是 INDEXED_PALETTE — 只有索引颜色文档才携带调色板。

Setting image.image_resources raises NotSupportedException. 此 setter 在此 FOSS 构建中不受支持;请将 image_resources and resources 视为只读。

常见问题

我可以直接修改 header、color data 或 image data 部分吗?

不——PsdHeader、PsdColorDataInfo、ColorData和PsdImageDataInfo都是此 FOSS 构建中的只读摘要对象。它们的属性没有任何公共 setter。

image.compression 和 image.image_data_kind 有什么区别?

它们通过两个独立的枚举来描述相同的底层编码:image.compression 返回一个 CompressionMethod 值,而 image.image_data_info.kind 返回一个 ImageDataKind 值。

另请参阅

 中文