psd_tools.api.layers

Layer module.

This module implements the high-level layer API for psd-tools, providing Pythonic interfaces for working with Photoshop layers. It defines the layer type hierarchy and common operations.

Key classes:

  • Layer: Base class for all layer types

  • GroupMixin: Mixin for layers that contain children (groups, documents)

  • Group: Folder/group layer containing other layers

  • PixelLayer: Regular raster layer with pixel data

  • TypeLayer: Text layer with typography information

  • ShapeLayer: Vector shape layer

  • SmartObjectLayer: Embedded or linked smart object

  • AdjustmentLayer: Non-destructive adjustment (curves, levels, etc.)

Layer hierarchy:

Layers are organized in a tree structure where groups can contain child layers. The GroupMixin provides iteration, indexing, and search capabilities:

# Iterate through all layers
for layer in psd:
    print(layer.name)

# Access by index
first_layer = psd[0]

# Check if layer is a specific type
if layer.kind == 'pixel':
    pixels = layer.toarray()

Common layer properties:

  • name: Layer name

  • visible: Visibility flag

  • opacity: Opacity (0-255)

  • blend_mode: Blend mode enum

  • bbox: Bounding box (left, top, right, bottom)

  • width, height: Dimensions

  • kind: Layer type string (‘pixel’, ‘group’, ‘type’, etc.)

  • parent: Parent layer or document

Layer operations:

Example usage:

from psd_tools import PSDImage

psd = PSDImage.open('document.psd')

# Access first layer
layer = psd[0]

# Modify layer properties
layer.visible = False
layer.opacity = 128
layer.name = "New Name"

# Get pixel data
pixels = layer.toarray()  # NumPy array
image = layer.topil()   # PIL Image

# Work with groups
for group in psd.descendants():
    if group.kind == 'group':
        print(f"Group: {group.name} with {len(group)} layers")

# Composite specific layer
rendered = layer.composite()
rendered.save('layer.png')

Layer types are automatically determined from the underlying PSD structures and exposed through the kind property for easy type checking.

Layer

class psd_tools.api.layers.Layer(parent: GroupMixin, record: LayerRecord, channels: ChannelDataList)[source]

Base class of the layers.

property bbox: tuple[int, int, int, int]

(left, top, right, bottom) tuple.

property blend_mode: BlendMode

Blend mode of this layer. Writable.

Example:

from psd_tools.constants import BlendMode
if layer.blend_mode == BlendMode.NORMAL:
    layer.blend_mode = BlendMode.SCREEN
Returns:

BlendMode.

property bottom: int

Bottom coordinate.

Returns:

int

property clip_layers: list[Self]

Clip layers associated with this layer.

Returns:

list of layers

property clipping: bool

Clipping flag for this layer. Writable.

Returns:

bool

composite(viewport: tuple[int, int, int, int] | None = None, force: bool = False, color: float | Sequence[float] | ndarray = 1.0, alpha: float | ndarray = 0.0, layer_filter: Callable | None = None, apply_icc: bool = True, include_effects: bool = False) → Image | None[source]

Composite layer and masks (mask, vector mask, and clipping layers).

Parameters:
  • viewport – Viewport bounding box specified by (x1, y1, x2, y2) tuple. Default is the layer’s bbox.

  • force – Boolean flag to force vector drawing.

  • color – Backdrop color, as a scalar, a per-channel sequence, or a full (height, width, channels) array. The color value should be in [0.0, 1.0]. For example, (1., 0., 0.) specifies red in RGB color mode.

  • alpha – Backdrop alpha in [0.0, 1.0].

  • layer_filter – Callable that takes a layer as argument and returns whether if the layer is composited. Default is is_visible().

  • include_effects – Use effects_bbox as the viewport, so effects that paint outside the layer are kept. Default is False, which keeps the output the size of bbox. Cannot be combined with viewport.

Returns:

PIL.Image.Image or None.

copy_to(group: GroupMixin, index: int | None = None) → Self[source]

Copy the layer into group, a group or document of any document.

The copy is deep, including a group’s descendants, and has fresh layer IDs. The source and its document are left as they were. Channels are converted to the destination’s colour mode, depth and file version; narrowing a 32-bit layer tone-maps as Photoshop does. The patterns and linked smart objects it uses are copied into the destination document, patterns unconverted to its colour mode. Clipping is positional: the layers clipped to this one are not copied, and a copy keeps its own clipping flag.

Parameters:
  • group – The destination Group or document.

  • index – The copy’s position in group afterwards, counting from the bottom; negative counts from the top, so -1 is the top. Default is the top.

Raises:
  • TypeError – If group is not a group or document, or index is not an integer.

  • ValueError – If group is a removed group or in a Bitmap, Indexed or Multichannel document, which cannot hold layers; an Artboard is not going to the document root; or the layer cannot be converted to the destination’s colour mode.

  • IndexError – If index is out of range.

Returns:

The inserted copy.

create_mask(image: Image, top: int | None = None, left: int | None = None, compression: Compression = Compression.RLE) → Mask[source]

Create a pixel mask on this layer from a PIL Image.

If the image has an alpha channel (e.g. RGBA, LA), the alpha channel is used as the mask data. Otherwise the image is converted to grayscale (L mode). White (255) means fully unmasked, black (0) means fully masked.

Parameters:
  • image – Source Image for the mask.

  • top – Top offset of the mask. Defaults to the layer’s top.

  • left – Left offset of the mask. Defaults to the layer’s left.

  • compression – Compression algorithm for the mask data.

Returns:

The new Mask.

Raises:

ValueError – If the layer already has a mask.

create_mask_from_array(array: ndarray, top: int | None = None, left: int | None = None, compression: Compression = Compression.RLE) → Mask[source]

Create a pixel mask on this layer from an array, at the document’s depth.

Unlike create_mask(), a 16- or 32-bit document keeps more than 8 bits. White (1.0) means fully unmasked, black (0.0) means fully masked.

Parameters:
  • array – (height, width) or (height, width, 1) array; float32 in [0, 1], uint8 or uint16.

  • top – Top offset of the mask. Defaults to the layer’s top.

  • left – Left offset of the mask. Defaults to the layer’s left.

  • compression – Compression algorithm for the mask data.

Returns:

The new Mask.

Raises:
  • TypeError – If the array is not a float, uint8 or uint16 numpy.ndarray.

  • ValueError – If the layer already has a mask, or the array is empty, non-finite, or not a single channel.

duplicate(parent: GroupMixin | None = None, *, index: int | None = None, name: str | None = None, offset: tuple[int, int] | None = None) → Self[source]

Deep-copy this layer, including a group’s descendants, in its document.

The copy retains its layer type, channels, masks and layer metadata, with fresh layer IDs. Document resources such as smart-object contents remain shared. No cached API wrappers are copied. An artboard’s copy is placed to the right of the source, as Photoshop does, and the document canvas is not resized to hold it.

Parameters:
  • parent – Destination group or document. Defaults to this layer’s parent. A detached layer requires an explicit destination.

  • index – The copy’s final position in the destination, counting from the bottom; negative counts from the top, so -1 is the top. Defaults to immediately above the source in the same parent, or the top of another container. A copy placed directly above its source releases the clipped layers above the source.

  • name – Optional name for the copy’s root layer.

  • offset – (dx, dy) pixels to move the copy by, with a group’s descendants, masks, vector paths and smart-object transforms moving along. Defaults to a gap of 100 pixels to the right of the source for an artboard, and no movement for any other layer; pass (0, 0) to keep an artboard on the source’s rectangle. A clipboard path record and legacy type data cannot be moved; they stay put with a warning.

Raises:
  • TypeError – If the destination, index, name or offset has an invalid type.

  • ValueError – If no destination is available, the destination is in another document, an artboard is not going to the document root, the name exceeds 255 characters, the offset exceeds 2**30 pixels, or it moves a vector path beyond what the file format can store.

  • IndexError – If index is out of range.

Returns:

The inserted copy; the source remains in place.

property effects: Effects

Layer effects.

A live view: the proxy re-reads the layer’s effects block on every access, so an edit made underneath shows through without it having to be discarded first. It holds no state worth memoising – building one costs a fraction of listing the effects once.

Returns:

Effects

property effects_bbox: tuple[int, int, int, int]

(left, top, right, bottom) tuple containing the layer’s effects.

bbox grown by the outward reach of each enabled effect that composite() renders, such as a stroke or a drop shadow. A group also covers the effects of its children. The box is a conservative envelope: it may hold transparent margin, and may widen as more effects are rendered. Equal to bbox when no effect reaches outside it.

property fill_opacity: int

Fill opacity of this layer in [0, 255] range. Writable.

Returns:

int

has_clip_layers(visible: bool = False) → bool[source]

Return True if the layer has associated clipping.

Parameters:

visible – If True, check for visible clipping layers.

Returns:

bool

has_effects(enabled: bool = True, name: str | None = None) → bool[source]

Return True if the layer has effects.

has_effects() asks “does this layer draw any effect?”: the master switch on and an entry enabled under it. has_effects(enabled=False) asks “does the fx list show anything?”, the same as len(layer.effects) > 0.

Neither tests for an effects tagged block, which Photoshop leaves behind after the last effect is removed; ask tagged_blocks for that (#318, #830).

Parameters:
  • enabled – If True, check for enabled effects.

  • name – If given, check for specific effect type.

Returns:

bool

has_mask() → bool[source]

Return True if the layer has a mask.

Returns:

bool

has_origination() → bool[source]

Return True if the layer has live shape properties.

Returns:

bool

has_pixels() → bool[source]

Whether the layer has associated pixels.

When True, the topil method returns PIL.Image.Image.

Returns:

bool

has_stroke() → bool[source]

Return True if the shape has a stroke.

has_vector_mask() → bool[source]

Return True if the layer has a vector mask.

Returns:

bool

property height: int

Height of the layer.

Returns:

int

is_group() → bool[source]

Return True if the layer is a group.

Returns:

bool

is_visible() → bool[source]

Layer visibility. Takes group visibility in account.

Returns:

bool

property kind: str

Kind of this layer.

One of group, pixel, shape, type, smartobject, or psdimage – the class name without its layer suffix.

Returns:

str

property layer_id: int

Layer ID.

Returns:

int layer id. if the layer is not assigned an id, -1.

property left: int

Left coordinate. Writable.

Returns:

int

lock(lock_flags: int = ProtectedFlags.COMPLETE) → None[source]

Locks a layer accordind to the combination of flags.

Parameters:

lockflags – An integer representing the locking state

Example using the constants of ProtectedFlags and bitwise or operation to lock both pixels and positions:

layer.lock(ProtectedFlags.COMPOSITE | ProtectedFlags.POSITION)
property locks: ProtectedSetting | None

Lock settings of the layer, or None if the layer has none.

property mask: Mask | None

Returns mask associated with this layer.

Returns:

Mask or None

move_down(offset: int = 1) → Self[source]

Move the layer down a certain offset within the group the layer is in.

Parameters:

offset – The number of positions to move the layer down (can be negative).

Raises:
  • ValueError – If the layer is not attached to a document

  • IndexError – If the new index is out of bounds

Returns:

self

move_to(parent: GroupMixin, *, index: int | None = None) → Self[source]

Move the layer into parent, a group or document of the same document.

A layer has one parent, so this moves rather than copies. A layer already at the requested position is left alone. Clipping is positional: the layers clipped to this one are not carried with it. Moving into a removed group removes the layer from the document.

Parameters:
  • parent – The destination Group or document.

  • index – The layer’s position in parent afterwards, counting from the bottom; negative counts from the top, so -1 is the top. Default is the top.

Raises:
  • ValueError – If parent is not a group or document of this layer’s document, the move would create a reference loop, or the layer is an Artboard and parent is not the document.

  • TypeError – If index is not an integer.

  • IndexError – If index is out of range.

Returns:

self

move_up(offset: int = 1) → Self[source]

Move the layer up a certain offset within the group the layer is in.

Parameters:

offset – The number of positions to move the layer up (can be negative).

Raises:
  • ValueError – If the layer is not attached to a document

  • IndexError – If the new index is out of bounds

Returns:

self

property name: str

Layer name. Writable.

Returns:

str

next_sibling(visible: bool = False) → Self | None[source]

Next sibling of this layer.

numpy(channel: str | None = None, real_mask: bool = True) → ndarray | None

Get NumPy array of the layer.

The inverse of fromarray(); numpy() is an alias.

Parameters:
  • channel – Which channel to return, can be ‘color’, ‘shape’, ‘alpha’, or ‘mask’. Default is ‘color+alpha’.

  • real_mask – Whether to use the real mask.

Returns:

numpy.ndarray or None if there is no pixel.

property offset: tuple[int, int]

(left, top) tuple. Writable.

Returns:

tuple

property opacity: int

Opacity of this layer in [0, 255] range. Writable.

Returns:

int

property origination: list[Origination]

Property for a list of live shapes or a line.

Some of the vector masks have associated live shape properties, that are Photoshop feature to handle primitive shapes such as a rectangle, an ellipse, or a line. Vector masks without live shape properties are plain path objects.

See psd_tools.api.shape.

Returns:

List of Invalidated, Rectangle, RoundedRectangle, Ellipse, or Line.

property parent: GroupMixinProtocol | None

Parent of this layer.

previous_sibling(visible: bool = False) → Self | None[source]

Previous sibling of this layer.

property reference_point: tuple[float, float]

Reference point of this layer as (x, y) tuple in the canvas coordinates. Writable.

Reference point is used for transformations such as rotation and scaling.

Returns:

(x, y) tuple

remove_mask() → None[source]

Remove the pixel mask from this layer.

Raises:

ValueError – If the layer does not have a mask.

property right: int

Right coordinate.

Returns:

int

property sheet_color: SheetColorType

Color label of this layer in the Photoshop layers panel. Writable.

Returns:

SheetColorType

property size: tuple[int, int]

(width, height) tuple.

Returns:

tuple

property stroke: Stroke | None

Property for strokes.

property tagged_blocks: TaggedBlocks

Layer tagged blocks that is a dict-like container of settings.

See psd_tools.constants.Tag for available keys.

Returns:

TaggedBlocks.

Example:

from psd_tools.constants import Tag
metadata = layer.tagged_blocks.get_data(Tag.METADATA_SETTING)
toarray(channel: str | None = None, real_mask: bool = True) → ndarray | None[source]

Get NumPy array of the layer.

The inverse of fromarray(); numpy() is an alias.

Parameters:
  • channel – Which channel to return, can be ‘color’, ‘shape’, ‘alpha’, or ‘mask’. Default is ‘color+alpha’.

  • real_mask – Whether to use the real mask.

Returns:

numpy.ndarray or None if there is no pixel.

property top: int

Top coordinate. Writable.

Returns:

int

topil(channel: int | None = None, apply_icc: bool = True) → Image | None[source]

Get PIL Image of the layer.

Parameters:
  • channel – Which channel to return; e.g., 0 for ‘R’ channel in RGB image. See ChannelID. When None, the method returns all the channels supported by PIL modes.

  • apply_icc – Whether to apply ICC profile conversion to sRGB.

Returns:

PIL.Image.Image, or None if the layer has no pixels.

Example:

from psd_tools.constants import ChannelID

image = layer.topil()
red = layer.topil(ChannelID.CHANNEL_0)
alpha = layer.topil(ChannelID.TRANSPARENCY_MASK)

Note

Not all of the PSD image modes are supported in PIL.Image.Image. For example, ‘CMYK’ mode cannot include alpha channel in PIL. In this case, topil drops alpha channel.

Note

PIL has no 16- or 32-bit RGB, CMYK or LAB mode, so a deep layer comes back with 8 bits per channel. Use numpy() for the stored precision.

unlock() → None[source]

Clear every lock of the layer.

update_mask(image: Image, top: int | None = None, left: int | None = None, compression: Compression = Compression.RLE) → Mask[source]

Update the pixel mask of this layer with a new image.

If the image has an alpha channel (e.g. RGBA, LA), the alpha channel is used as the mask data. Otherwise the image is converted to grayscale (L mode). White (255) means fully unmasked, black (0) means fully masked.

Parameters:
  • image – New source Image for the mask.

  • top – New top offset of the mask. Defaults to current mask top.

  • left – New left offset of the mask. Defaults to current mask left.

  • compression – Compression algorithm for the mask data.

Returns:

The updated Mask.

Raises:

ValueError – If the layer does not have a mask.

update_mask_from_array(array: ndarray, top: int | None = None, left: int | None = None, compression: Compression = Compression.RLE) → Mask[source]

Update the pixel mask of this layer from an array, at the document’s depth.

See create_mask_from_array() for the accepted arrays.

Parameters:
  • array – New mask array.

  • top – New top offset of the mask. Defaults to current mask top.

  • left – New left offset of the mask. Defaults to current mask left.

  • compression – Compression algorithm for the mask data.

Returns:

The updated Mask.

Raises:
  • TypeError – If the array is not a float, uint8 or uint16 numpy.ndarray.

  • ValueError – If the layer does not have a mask, or the array is empty, non-finite, or not a single channel.

property vector_mask: VectorMask | None

Returns vector mask associated with this layer.

Returns:

VectorMask or None

property visible: bool

Layer visibility. Doesn’t take group visibility in account. Writable.

Returns:

bool

property width: int

Width of the layer.

Returns:

int

GroupMixin

class psd_tools.api.layers.GroupMixin[source]

Container behaviour shared by groups and documents.

Group and PSDImage both hold an ordered list of child layers, and this mixin supplies what operates on it: iteration and indexing, the mutation methods below, the descendants() walk, and a bbox computed from the visible, non-clipping children.

A layer belongs to at most one container, so adding one that already has a parent moves it out of that parent rather than copying it; see extend(). The list methods here are a fixed set: sort(), reverse(), +=, copy() and slice assignment or deletion are not provided.

__delitem__(key: int) → None[source]

Remove the layer at the specified index from the group.

This operation rewrites the internal references of the layer.

Parameters:

key – The index of the layer to remove.

Raises:
__getitem__(key: int) → Layer[source]

Get child layer by index.

__iter__() → Iterator[Layer][source]

Iterate over child layers.

__len__() → int[source]

Return the number of child layers.

append(layer: Layer) → None[source]

Add a layer to the end (top) of the group.

This operation rewrites the internal references of the layer. Adding the same layer will not create a duplicate; it moves to the end instead. See extend(), which this delegates to.

Parameters:

layer – The layer to add.

Raises:
  • TypeError – If the provided object is not a Layer instance.

  • ValueError – If attempting to add a group to itself, or a layer of another document; use copy_to().

property bbox: tuple[int, int, int, int]

(left, top, right, bottom) tuple computed from visible, non-clipping children.

clear() → None[source]

Clear the group.

This operation rewrites the internal references of the layers.

Returns:

None

count(layer: Layer) → int[source]

Return 1 if the layer is a child of this container, else 0.

Adding a layer that is already here moves it, so it never appears twice.

Parameters:

layer – The layer to count.

create_group(layer_list: Iterable[Layer] | None = None, name: str = 'Group', opacity: int = 255, blend_mode: BlendMode = BlendMode.PASS_THROUGH, open_folder: bool = True) → Group[source]

Create a new group at the top of this group or document.

Example:

group = psdimage.create_group(name='New Group')
layer = group.create_pixel_layer(image, name='Layer in Group')
Parameters:
  • layer_list – Optional iterable of layers to add to the group.

  • name – Name of the new group.

  • opacity – Opacity of the new layer (0-255).

  • blend_mode – Blend mode of the new layer, default is BlendMode.PASS_THROUGH.

  • open_folder – Whether the group is an open folder in the Photoshop UI.

Returns:

The created Group object.

create_pixel_layer(image: Image, name: str = 'Layer', top: int = 0, left: int = 0, compression: Compression = Compression.RLE, opacity: int = 255, blend_mode: BlendMode = BlendMode.NORMAL) → PixelLayer[source]

Create a new pixel layer at the top of this group or document.

Example:

psdimage = PSDImage.new("RGB", (640, 480))
layer = psdimage.create_pixel_layer(image, name='Layer 1')
Parameters:
  • name – Name of the new layer.

  • image – PIL Image object. On a 16- or 32-bit document the layer is stored at the document’s depth, carrying the image’s own 8-bit precision; use create_pixel_layer_from_array() to keep more.

  • top – Top coordinate of the new layer.

  • left – Left coordinate of the new layer.

  • compression – Compression method for the layer image data.

  • opacity – Opacity of the new layer (0-255).

  • blend_mode – Blend mode of the new layer, default is BlendMode.NORMAL.

Returns:

The created PixelLayer object.

create_pixel_layer_from_array(array: ndarray, name: str = 'Layer', top: int = 0, left: int = 0, compression: Compression = Compression.RLE, opacity: int = 255, blend_mode: BlendMode = BlendMode.NORMAL) → PixelLayer[source]

Create a new pixel layer from an array at the document’s full precision.

Unlike create_pixel_layer(), a 16- or 32-bit document keeps more than 8 bits; see fromarray() for the accepted arrays.

Example:

psdimage = PSDImage.new("RGB", (640, 480), depth=16)
array = np.random.rand(480, 640, 3).astype(np.float32)
layer = psdimage.create_pixel_layer_from_array(array)
Parameters:
  • array – float32 in [0, 1], uint8 or uint16 array.

  • name – Name of the new layer.

  • top – Top coordinate of the new layer.

  • left – Left coordinate of the new layer.

  • compression – Compression method for the layer image data.

  • opacity – Opacity of the new layer (0-255).

  • blend_mode – Blend mode of the new layer, default is BlendMode.NORMAL.

Returns:

The created PixelLayer object.

descendants(include_clip: bool = True) → Iterator[Layer][source]

Return a generator to iterate over all descendant layers.

Parameters:

include_clip – Whether to include clipping layers. Default is True.

Example:

# Iterate over all layers
for layer in psd.descendants():
    print(layer)

# Iterate over all layers in reverse order
for layer in reversed(list(psd.descendants())):
    print(layer)
extend(layers: Iterable[Layer]) → None[source]

Add layers to the end (top) of the group.

This operation rewrites the internal references of the layers. A layer named more than once, or already in this group, ends up once, at the position of its last mention, as a loop of append() calls leaves it. The iterable is walked once, so a generator or a live container being emptied into this group is accepted:

dest.extend(src)  # Moves every layer of src into dest.
Parameters:

layers – The layers to add.

Raises:
  • TypeError – If the provided object is not a Layer instance.

  • ValueError – If attempting to add a group to itself, or a layer of another document; use copy_to().

find(name: str) → Layer | None[source]

Return the first layer found for the given layer name.

Parameters:

name

findall(name: str) → Iterator[Layer][source]

Return a generator to iterate over all layers with the given name.

Parameters:

name

index(layer: Layer) → int[source]

Return the index of the specified layer in the group.

Parameters:

layer – The layer to find.

insert(index: int, layer: Layer) → None[source]

Insert the given layer at the specified index.

This operation rewrites the internal references of the layer. A layer already in this group is moved rather than copied, following the no-duplicates rule of extend(), so the index it lands at is one lower than the given one when it came from before that position.

Parameters:
  • index – The index to insert the layer at.

  • layer – The layer to insert.

Raises:
  • TypeError – If the provided object is not a Layer instance.

  • ValueError – If attempting to add a group to itself, or a layer of another document; use copy_to().

is_group() → bool[source]

Return True if this is a group.

is_visible() → bool[source]

Return visibility of the element.

pop(index: int = -1) → Layer[source]

Remove the specified layer from the list and return it.

This operation rewrites the internal references of the layer.

Parameters:

index – The index of the layer to remove. Default is -1 (the last layer).

Raises:

IndexError – If the index is out of range.

Returns:

The removed layer.

remove(layer: Layer) → Self[source]

Remove the specified layer from the group.

This operation rewrites the internal references of the layer.

Parameters:

layer – The layer to remove.

Raises:

ValueError – If the layer is not found in the group.

Returns:

self

Artboard

class psd_tools.api.layers.Artboard(parent: GroupMixin, record: LayerRecord, channels: ChannelDataList)[source]

Artboard is a special kind of group that has a pre-defined viewbox.

property background: ArtboardBackground

The artboard’s background setting, as stored in the file.

Unlike what composite() applies, the result does not depend on the document color mode: the color is always RGB, so a custom color on a CMYK or Lab document is reported as RGB. A missing, malformed or unknown setting reads as transparent.

property bbox: tuple[int, int, int, int]

(left, top, right, bottom) tuple.

property bottom: int

Bottom coordinate of the bounding box.

composite(viewport: tuple[int, int, int, int] | None = None, force: bool = False, color: float | Sequence[float] | ndarray | None = None, alpha: float | ndarray | None = None, layer_filter: Callable | None = None, apply_icc: bool = True, include_effects: bool = False) → Image | None[source]

Composite layer, automatically applying the artboard’s background color.

When either color or alpha is not explicitly provided, reads the artboard background from the ARTBOARD_DATA tagged block (artboardBackgroundType and Clr descriptor) and uses the missing value or values as the compositing backdrop. See Group.composite() for the other parameters.

property left: int

Left coordinate of the bounding box.

property right: int

Right coordinate of the bounding box.

property top: int

Top coordinate of the bounding box.

class psd_tools.api.layers.ArtboardBackground(kind: Literal['transparent', 'white', 'black', 'custom'], color: tuple[float, float, float] | None, alpha: float)[source]

Background of an Artboard, independent of the document color mode.

alpha: float

0.0 for a transparent background, 1.0 otherwise.

color: tuple[float, float, float] | None

RGB in [0.0, 1.0], or None for a transparent background.

kind: Literal['transparent', 'white', 'black', 'custom']

Photoshop’s background setting.

Group

class psd_tools.api.layers.Group(parent: GroupMixin, record: LayerRecord, channels: ChannelDataList)[source]

Group of layers.

Example:

group = psd[1]
for layer in group:
    if layer.kind == 'pixel':
        print(layer.name)
property blend_mode: BlendMode

Blend mode of this layer. Writable.

property bottom: int

Bottom coordinate (computed from children, read-only).

property clipping: bool

Clipping flag for this layer. Writable.

Returns:

bool

composite(viewport: tuple[int, int, int, int] | None = None, force: bool = False, color: float | Sequence[float] | ndarray = 1.0, alpha: float | ndarray = 0.0, layer_filter: Callable | None = None, apply_icc: bool = True, include_effects: bool = False) → Image | None[source]

Composite layer and masks (mask, vector mask, and clipping layers).

Parameters:
  • viewport – Viewport bounding box specified by (x1, y1, x2, y2) tuple. Default is the layer’s bbox.

  • force – Boolean flag to force vector drawing.

  • color – Backdrop color, as a scalar, a per-channel sequence, or a full (height, width, channels) array. The color value should be in [0.0, 1.0]. For example, (1., 0., 0.) specifies red in RGB color mode.

  • alpha – Backdrop alpha in [0.0, 1.0].

  • layer_filter – Callable that takes a layer as argument and returns whether if the layer is composited. Default is is_visible().

  • include_effects – Use effects_bbox as the viewport, so effects that paint outside the layer are kept. Default is False, which keeps the output the size of bbox. Cannot be combined with viewport.

Returns:

PIL.Image.Image.

static extract_bbox(layers: Sequence[Layer] | GroupMixin, include_invisible: bool = False, include_clipping: bool = False) → tuple[int, int, int, int][source]

Return a bounding box for layers.

Gives (0, 0, 0, 0) if the layers have no bounding box.

Parameters:
  • layers – sequence of layers or a group.

  • include_invisible – include invisible layers in calculation.

  • include_clipping – include clipping layers in calculation. Defaults to False to match visible pixel bounds.

Returns:

tuple of four int

is_group() → bool[source]

Return True if the layer is a group.

Returns:

bool

property left: int

Left coordinate (computed from children, read-only).

classmethod new(parent: GroupMixin, name: str = 'Group', open_folder: bool = True) → Self[source]

Create a new Group object.

Builds the minimal records, data channels and metadata needed to include the group in the PSD file.

Parameters:
  • name – The display name of the group. Default to “Group”.

  • open_folder – Boolean defining whether the folder will be open or closed in photoshop. Default to True.

  • parent – Optional parent folder to move the newly created group into.

Returns:

A Group object

Raises:

ValueError – If parent is None

property open_folder: bool

Returns True if the group is an open folder.

Returns:

bool

property right: int

Right coordinate (computed from children, read-only).

property top: int

Top coordinate (computed from children, read-only).

PixelLayer

class psd_tools.api.layers.PixelLayer(parent: GroupMixin, record: LayerRecord, channels: ChannelDataList)[source]

Layer that has rasterized image in pixels.

Example:

assert layer.kind == 'pixel':
image = layer.composite()
image.save('layer.png')
classmethod fromarray(array: ndarray, parent: GroupMixin, name: str = 'Layer', top: int = 0, left: int = 0, compression: Compression = Compression.RLE, **kwargs: Any) → PixelLayer[source]

Create a PixelLayer from an array at the document’s full precision.

The inverse of toarray(): a layer read back with toarray() returns the array given here, to the precision of the document’s depth.

Parameters:
  • array – (height, width, channels) array, or (height, width) for a single channel. channels is the colour mode’s colour channel count, with one more for the layer’s transparency; a layer without it is opaque. Floating point values are in [0, 1] (32-bit documents also keep values outside it); uint8 and uint16 are scaled by their maximum. Values are in the stored convention numpy() returns, so a CMYK layer holds 255 for no ink.

  • parent – The parent group or PSDImage this layer belongs to.

  • name – The name of the layer. Defaults to “Layer”

  • top – Pixelwise offset from the top of the canvas for the new layer.

  • left – Pixelwise offset from the left of the canvas for the new layer.

  • compression – Compression algorithm to use for the data.

Returns:

A PixelLayer object

Raises:
  • TypeError – If the array is not a float, uint8 or uint16 numpy.ndarray

  • ValueError – If parent is None, or the array is empty, non-finite, or of the wrong shape for the document’s colour mode, or the document is indexed

classmethod frompil(image: Image, parent: GroupMixin, name: str = 'Layer', top: int = 0, left: int = 0, compression: Compression = Compression.RLE, **kwargs: Any) → PixelLayer[source]

Create a PixelLayer from a PIL image for a given psd file.

Parameters:
  • image – The Image object to convert to photoshop

  • parent – The parent group or PSDImage this layer belongs to.

  • name – The name of the layer. Defaults to “Layer”

  • top – Pixelwise offset from the top of the canvas for the new layer.

  • left – Pixelwise offset from the left of the canvas for the new layer.

  • compression – Compression algorithm to use for the data.

Returns:

A PixelLayer object

Raises:

Note

If the image has an alpha channel and the parent PSD mode supports layer transparency (e.g. RGBA, LA), the alpha is stored as the layer transparency channel and no extra mask is created. For PSD modes that do not carry a transparency band (e.g. RGB, CMYK), the alpha channel is instead stored as a pixel mask (USER_LAYER_MASK).

Note

On a 16- or 32-bit document the layer is stored at the document’s depth but with a PIL image’s precision, which is 8 bits: PIL has no 16-bit RGB, CMYK or LAB mode to carry more, and the image is converted to pil_mode on the way in. The values are widened, not padded – 128 becomes 32896 at depth 16 – so the layer reads back as the image given here. Use fromarray() to keep more precision.

ShapeLayer

class psd_tools.api.layers.ShapeLayer(*args: Any)[source]

Layer that has drawing in vector mask.

property bbox: tuple[int, int, int, int]

(left, top, right, bottom) tuple.

property bottom: int

Bottom coordinate of the bounding box.

property left: int

Left coordinate of the bounding box.

property right: int

Right coordinate of the bounding box.

property top: int

Top coordinate of the bounding box.

SmartObjectLayer

class psd_tools.api.layers.SmartObjectLayer(parent: GroupMixin, record: LayerRecord, channels: ChannelDataList)[source]

Layer that inserts external data.

Use smart_object attribute to get the external data. See SmartObject.

Example:

import io
so = layer.smart_object
if so.detected_filetype == 'jpg':
    # Use open(external_dir=...) when processing untrusted PSD files.
    with so.open() as f:
        image = Image.open(io.BytesIO(f.read()))
property smart_object: SmartObject

Associated smart object.

Returns:

SmartObject.

TypeLayer

class psd_tools.api.layers.TypeLayer(*args: Any)[source]

Layer that has text and styling information for fonts or paragraphs.

Text is accessible at text property. Styling information for paragraphs is in engine_dict. Document styling information such as font list is is resource_dict.

Currently, textual information is read-only.

Example:

if layer.kind == 'type':
    print(layer.text)
    print(layer.engine_dict['StyleRun'])

    # Extract font for each substring in the text.
    text = layer.engine_dict['Editor']['Text'].value
    fontset = layer.resource_dict['FontSet']
    runlength = layer.engine_dict['StyleRun']['RunLengthArray']
    rundata = layer.engine_dict['StyleRun']['RunArray']
    index = 0
    for length, style in zip(runlength, rundata):
        substring = text[index:index + length]
        stylesheet = style['StyleSheet']['StyleSheetData']
        font = fontset[stylesheet['Font']]
        print('%r gets %s' % (substring, font))
        index += length
property document_resources: Dict

Resource set relevant to the document.

property engine_dict: Dict

Styling information dict; empty if the engine data is unreadable.

property font_names: list[str]

List of PostScript font names used in this text layer.

Convenience shortcut for:

[font.postscript_name for font in layer.typesetting.fonts]
property resource_dict: Dict

Resource set.

property text: str

Text in the layer. Read-only.

Note

New-line character in Photoshop is '\r'.

property text_type: TextType | None

Text type. Read-only.

Returns:

See psd_tools.constants.TextType.

property transform: tuple[float, float, float, float, float, float]

Matrix (xx, xy, yx, yy, tx, ty) applies affine transformation.

property typesetting: TypeSetting

Structured typographic data.

Returns a TypeSetting object that provides Pythonic access to fonts, paragraphs, styled runs, and default styles without navigating raw engine data dicts.

Example:

ts = layer.typesetting
for paragraph in ts:
    print(paragraph.style.justification)
    for run in paragraph.runs:
        print(run.text, run.style.font_name, run.style.font_size)

See also: engine_dict, resource_dict for raw data.

property warp: DescriptorBlock | None

Warp configuration.