如何在 Python 中使用 PSD 图层

如何在 Python 中使用 PSD 图层

本指南展示了如何列出文档的图层、读取和更改可编辑的图层元数据、重新定位图层以及从集合中移除图层。已加载的 PsdImage 的 layers 属性返回其 Layer 对象集合。每个 Layer 都公开可编辑的元数据——名称、可见性、不透明度、剪裁、混合模式和位置(边界边缘)——以及只读的整体边界和通道信息。

分步指南

步骤 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 加载文档;BlendMode 稍后用于设置图层的混合模式:

from aspose_psd_foss.psdimage import PsdImage
from aspose_psd_foss.layers.blendmode import BlendMode

步骤 3:加载文档并列出其图层

加载文档,然后遍历 layers 以查看每个图层的名称和几何信息:

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

for layer in image.layers:
    print(f"{layer.name}: {layer.width}x{layer.height} at ({layer.left},{layer.top})")

步骤 4:读取并编辑图层的可见性、不透明度和混合模式

is_visible、opacity(通常为 0-255)、clipping、name 和 blend_mode_key 都具有可用的 setter:

layer = image.layers[0]

layer.is_visible = False          # hide the layer
layer.opacity = 200               # ~78% opacity
layer.blend_mode_key = BlendMode.MULTIPLY
layer.name = "Renamed Layer"

步骤 5:读取并重新定位图层边界

bounds、width、height 和 channels_count 为只读——但 top、left、bottom 和 right 每个都有可用的 setter 可重新定位图层:

print(f"Bounds: {layer.bounds}")
print(f"Channels: {layer.channels_count}")

layer.left = 10
layer.top = 20
layer.right = 40
layer.bottom = 60

步骤 6:替换图层集合

PsdImage.layers 本身具有可用的 setter,因此您可以替换整个集合(例如,移除某个图层):

image.layers = [l for l in image.layers if l.name != "Renamed Layer"]

步骤 7:保存文档

将前面步骤中所做的所有编辑写回磁盘,然后释放图像资源:

image.save("output.psd")
image.dispose()

常见问题与解决方案

NotSupportedException 在设置时 channel_information, layer_mask_data,或 layer_blending_ranges_data. 这三个 Layer setters are not supported in this FOSS build — treat them as read-only. 在此 FOSS 构建中不支持这些 setter——请将它们视为只读。

Opacity value looks wrong after setting it. 设置后不透明度值看起来不对。 opacity is conventionally a 0-255 value, not a 0.0-1.0 fraction or a percentage — 通常是 0-255 的取值,而不是 0.0-1.0 的小数或百分比—— layer.opacity = 200 means roughly 78% opaque (200/255). 大约等于 78% 不透明(200/255)。

Changes to a layer don’t appear after saving. 对图层的更改保存后未显示。 确认您正在修改 Layer 获取的实例 image.layers,并且您调用 image.save() 在完成编辑后。

常见问题

我可以从文档中删除图层吗?

是的 — PsdImage.layers 有可用的 setter,因此您可以为其分配一个过滤列表以删除图层(参见第 6 步)。

有哪些可用的混合模式?

BlendMode 包含诸如 NORMAL、MULTIPLY、SCREEN、OVERLAY 和 DARKEN 等值 — 通过 Layer.blend_mode_key 设置。

是否可以获取图层蒙版数据?

Layer.layer_mask_data 有可用的 getter,但在此 FOSS 构建中,其 setter 会抛出 NotSupportedException。

另请参阅

 中文