如何在 Python 中使用 PSD 图像资源

如何在 Python 中使用 PSD 图像资源

已加载的 PsdImage 通过两个只读视图公开其图像资源块——类似元数据的条目,如网格、参考线和 ICC 配置文件负载——以及针对索引颜色调色板的单独摘要。

分步指南

步骤 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
from aspose_psd_foss.resources.imageresourceids import ImageResourceIds

步骤 3:检查并计数图像资源

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

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

步骤 4:通过 image_resources 列出资源块

PsdImage.image_resources 为每个资源返回一个 PreservedResourceBlock,其中包含原始资源 ID、名称和字节大小:

for block in image.image_resources:
    print(f"ID: {block.id}, name: {block.name!r}, size: {block.size} bytes")

通过将 block.id 与 ImageResourceIds 中已知的常量进行比较来识别特定资源:

for block in image.image_resources:
    if block.id == ImageResourceIds.ICC_PROFILE:
        print(f"Found an ICC profile resource ({block.data_size} bytes)")

此 FOSS 构建的资源解析器本身不会将资源 ID 解码为语义属性——自行将 block.id 与 ImageResourceIds 进行比较是识别特定资源的受支持方式。


步骤 5:通过 resources 列出资源摘要

PsdImage.resources 为每个资源返回一个单独的 PsdResourceInfo 摘要,包含 kind 分类:

for info in image.resources:
    print(f"ID: {info.resource_id}, kind: {info.kind}, data length: {info.data_length}")

在此 FOSS 构建中,kind 始终为 PsdResourceKind.UNKNOWN —— 未实现对特定资源类型(全局角度、ICC 配置文件)的语义分类,因此仅将 kind 视为信息性,并依赖 resource_id(步骤 4)来识别特定资源。


步骤 6:读取索引颜色调色板

如果文档的颜色数据基于调色板,PsdImage.indexed_palette 将返回其条目:

palette = image.indexed_palette

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

常见问题与解决方案

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

Setting image.image_resources raises NotSupportedException. getter 可用于列出资源,但在此 FOSS 构建中不支持 setter。

Calling block.save() 在一个 PreservedResourceBlock raises NotImplementedError. 不支持直接保存单个资源块 — 当您调用时,资源会自动往返 image.save() 在整个文档上。

has_icc_profile, is_icc_profile_untagged,并且 global_angle 永不改变。 这三个 PsdImage 属性在此 FOSS 构建中是固定的占位符值(has_icc_profile 始终是 False, is_icc_profile_untagged 始终是 None, global_angle 始终是 0)无论加载的文档实际内容如何——此构建的资源解析器不会重新构建 ID-specific 语义值。使用 Step 4’s block.id 比较对照 ImageResourceIds 如果您需要自行检测这些资源。

常见问题解答

image_resources 和 resources 有什么区别?

两者列出相同的底层资源块,但作为不同的对象类型:image_resources 返回 PreservedResourceBlock 对象(原始 ID/名称/大小,用于往返),而 resources 返回 PsdResourceInfo 摘要(添加了 kind 分类,当前始终为 UNKNOWN)。

我可以修改或删除镜像资源吗?

不——image_resources 的 setter 会抛出 NotSupportedException,如果直接调用,PreservedResourceBlock.save() 会抛出 NotImplementedError。在此 FOSS 构建中,资源是只读的。

另请参阅

 中文