如何在 Python 中使用 Aspose.PSD FOSS Core API
Aspose.PSD FOSS for Python 通过 PsdImage(Image 的子类)加载并检查 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:导入所需类
PsdImage 是本指南中贯穿使用的入口点:
from aspose_psd_foss.psdimage import PsdImage步骤 3:加载 PSD/PSB 文档
PsdImage.load() 从文件路径或流打开文档:
from aspose_psd_foss.psdimage import PsdImage
image = PsdImage.load("input.psd")步骤 4:检查文档头部
PsdImage 暴露从解析的文档中读取的头部字段:width、height、bits_per_channel、color_mode(ColorModes 值),以及 compression(CompressionMethod 值):
print(f"{image.width}x{image.height}, {image.bits_per_channel} bpc")
print(f"Color mode: {image.color_mode}") # e.g. ColorModes.RGB
print(f"Compression: {image.compression}") # e.g. CompressionMethod.RLE
print(f"Flattened: {image.is_flatten}")ColorModes 值包括 BITMAP、GRAYSCALE、INDEXED、RGB、CMYK、MULTICHANNEL、DUOTONE 和 LAB。CompressionMethod 值包括 RAW、RLE、ZIP_WITHOUT_PREDICTION 和 ZIP_WITH_PREDICTION。
步骤 5:读取图像资源块
image_resources 返回文档解析后的 ResourceBlock 条目。每个块暴露 id、name 和 size:
for resource in image.image_resources:
print(f"Resource {resource.id} \"{resource.name}\" - {resource.size} bytes")image_resources 在此 FOSS 构建中是只读的——对其赋值会引发 NotSupportedException (请参见已知限制中的 FAQ).
第6步:保存文档
将文档写回磁盘,然后释放图像资源:
image.save("output.psd")
image.dispose()常见问题及解决方案
PsdLoadException 在加载文件时。 输入不是有效的 PSD/PSB 文档,或其标题未通过验证。请在加载前确认该文件是真正的 PSD/PSB 文件。
NotSupportedException 在设置时 image_resources or global_layer_resources. 此 FOSS 构建不支持这些 setter。请将 image_resources 视为只读。
常见问答
我可以从流而不是文件路径加载 PSD 文件吗?
是的 — PsdImage.load() 接受文件路径字符串或可读流 (io.BytesIO/io.BufferedIOBase)。
image_resources 包含图层数据吗?
否。 image_resources 保存文档级资源块(从 PSD 图像资源部分解析而来)。图层级数据通过 PsdImage.layers — 参见 使用图层.
PsdImage.version 是 PSD 文件格式版本吗?
不。PsdImage.version 报告内部的 Aspose.PSD 兼容 API 版本号(当前为 6)——它与加载的文件是 PSD 还是 PSB 无关。其 setter 仅接受值 6;任何其他值都会触发 ValueError。