Layers

Layers

PsdImage.layers 将每个已解析的图层返回为一个 Layer 对象列表。每个 Layer 都公开其几何、可见性和合成状态,以及其通道、蒙版和混合范围的元数据。


读取图层元数据

name、bounds(以及派生的 width/height/top/left/bottom/right)、is_visible、opacity、clipping、blend_mode_key 和 channels_count 都可以直接读取。

from aspose_psd_foss.psdimage import PsdImage

with PsdImage.load("input.psd") as image:
    for layer in image.layers:
        print(f"{layer.name}: {layer.bounds}, "
              f"Visible={layer.is_visible}, Opacity={layer.opacity}, "
              f"BlendMode={layer.blend_mode_key}")

支持的元数据编辑

name、is_visible、opacity、clipping、blend_mode_key,以及四个边界边缘(top/left/bottom/right)可以原地修改,并使用 PsdImage.save() 写回。

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

with PsdImage.load("input.psd") as image:
    layer = image.layers[0]
    layer.name = f"{layer.name} (edited)"
    layer.is_visible = not layer.is_visible
    layer.opacity = 128
    layer.blend_mode_key = BlendMode.MULTIPLY
    image.save("output.psd")

通道和蒙版元数据

channel_information、layer_mask_data和layer_blending_ranges_data在此 FOSS 构建中为只读——它们的设置器会抛出 NotSupportedException。

layer = image.layers[0]
for channel in layer.channel_information:
    print(f"Channel {channel.ChannelID}: {channel.compression_method}, {channel.length} bytes")

if layer.has_mask_data:
    mask = layer.layer_mask_data
    print(f"Mask bounds: {mask.mask_rectangle}, flags: {mask.flags}")

删除或重新排序图层

PsdImage.layers 既有 setter 也有 getter:分配经过过滤或重新排序的列表会替换文档的图层集合。

from aspose_psd_foss.psdimage import PsdImage

with PsdImage.load("input.psd") as image:
    image.layers = [layer for layer in image.layers if layer.is_visible]
    image.save("output.psd")

技巧与最佳实践

  • 通过位置索引 image.layers;列表顺序与文档自身的图层顺序相匹配。
  • blend_mode_key 接受任意 BlendMode 枚举值——不会针对文档声明的颜色模式进行验证。
  • channel_information、layer_mask_data和layer_blending_ranges_data可以读取,但永不可重新赋值。
  • 在所有编辑完成后调用一次 PsdImage.save();每次调用都会写入完整文档。

常见问题

问题原因修复
在设置 channel_information、layer_mask_data 或 layer_blending_ranges_data 时 NotSupportedException尽管拥有 setter,这三个属性在 FOSS 构建中是只读的读取该值;不要尝试重新赋值
在没有遮罩时对 layer_mask_data 的访问并非每个图层都有遮罩子部分在读取 layer.layer_mask_data 之前检查 layer.has_mask_data

FAQ

我可以删除图层吗?

是的 — 将 image.layers 重新分配为过滤后的列表。

我可以更改图层的通道或蒙版数据吗?

不。channel_information、layer_mask_data 和 layer_blending_ranges_data 为只读 — 只有 name、is_visible、opacity、clipping、blend_mode_key 以及边界边缘可以更改。


API Reference 摘要

类/方法描述
PsdImage.layers获取或设置图层集合 — 可设置用于删除/重新排序
Layer.name / is_visible / opacity / clipping / blend_mode_key / top / left / bottom / right支持的图层元数据编辑
Layer.bounds / width / height / channels_count只读图层几何
Layer.channel_information / layer_mask_data / layer_blending_ranges_data只读通道/遮罩/混合元数据

另请参阅

 中文