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 typesGroupMixin: Mixin for layers that contain children (groups, documents)Group: Folder/group layer containing other layersPixelLayer: Regular raster layer with pixel dataTypeLayer: Text layer with typography informationShapeLayer: Vector shape layerSmartObjectLayer: Embedded or linked smart objectAdjustmentLayer: 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 namevisible: Visibility flagopacity: Opacity (0-255)blend_mode: Blend mode enumbbox: Bounding box (left, top, right, bottom)width,height: Dimensionskind: Layer type string (‘pixel’, ‘group’, ‘type’, etc.)parent: Parent layer or document
Layer operations:
composite(): Render layer to PIL Imagetoarray(): Get pixel data as NumPy arraytopil(): Convert to PIL Imagehas_mask(): Check if layer has a maskhas_clip_layers(): Check if layer has clipping mask
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 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:
- 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_bboxas the viewport, so effects that paint outside the layer are kept. Default is False, which keeps the output the size ofbbox. Cannot be combined withviewport.
- Returns:
PIL.Image.Imageor 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
Groupor document.index – The copy’s position in
groupafterwards, counting from the bottom; negative counts from the top, so-1is the top. Default is the top.
- Raises:
TypeError – If
groupis not a group or document, orindexis not an integer.ValueError – If
groupis a removed group or in a Bitmap, Indexed or Multichannel document, which cannot hold layers; anArtboardis not going to the document root; or the layer cannot be converted to the destination’s colour mode.IndexError – If
indexis 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 (
Lmode). White (255) means fully unmasked, black (0) means fully masked.- Parameters:
image – Source
Imagefor 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;float32in [0, 1],uint8oruint16.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,
uint8oruint16numpy.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
-1is 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
indexis 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:
- property effects_bbox: tuple[int, int, int, int]
(left, top, right, bottom) tuple containing the layer’s effects.
bboxgrown by the outward reach of each enabled effect thatcomposite()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 tobboxwhen no effect reaches outside it.
- 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 aslen(layer.effects) > 0.Neither tests for an effects tagged block, which Photoshop leaves behind after the last effect is removed; ask
tagged_blocksfor that (#318, #830).- Parameters:
enabled – If True, check for enabled effects.
name – If given, check for specific effect type.
- Returns:
bool
- has_pixels() bool[source]
Whether the layer has associated pixels.
When True, the topil method returns
PIL.Image.Image.- 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
- 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.
- 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
Groupor document.index – The layer’s position in
parentafterwards, counting from the bottom; negative counts from the top, so-1is the top. Default is the top.
- Raises:
ValueError – If
parentis not a group or document of this layer’s document, the move would create a reference loop, or the layer is anArtboardandparentis not the document.TypeError – If
indexis not an integer.IndexError – If
indexis 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
- 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.ndarrayor None if there is no pixel.
- 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, orLine.
- property parent: GroupMixinProtocol | None
Parent 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 sheet_color: SheetColorType
Color label of this layer in the Photoshop layers panel. Writable.
- Returns:
SheetColorType
- property tagged_blocks: TaggedBlocks
Layer tagged blocks that is a dict-like container of settings.
See
psd_tools.constants.Tagfor available keys.- Returns:
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.ndarrayor None if there is no pixel.
- 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.
- 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 (
Lmode). White (255) means fully unmasked, black (0) means fully masked.- Parameters:
image – New source
Imagefor 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,
uint8oruint16numpy.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:
VectorMaskor None
GroupMixin
- class psd_tools.api.layers.GroupMixin[source]
Container behaviour shared by groups and documents.
GroupandPSDImageboth hold an ordered list of child layers, and this mixin supplies what operates on it: iteration and indexing, the mutation methods below, thedescendants()walk, and abboxcomputed 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:
IndexError – If the index is out of range.
TypeError – If the key is not an index.
- 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
Groupobject.
- 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
PixelLayerobject.
- 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; seefromarray()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 –
float32in [0, 1],uint8oruint16array.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
PixelLayerobject.
- 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().
- 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.
- 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
colororalphais not explicitly provided, reads the artboard background from the ARTBOARD_DATA tagged block (artboardBackgroundTypeandClrdescriptor) and uses the missing value or values as the compositing backdrop. SeeGroup.composite()for the other parameters.
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)
- 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_bboxas the viewport, so effects that paint outside the layer are kept. Default is False, which keeps the output the size ofbbox. Cannot be combined withviewport.
- Returns:
- 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
- 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
Groupobject- Raises:
ValueError – If parent is None
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 withtoarray()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.channelsis 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);uint8anduint16are scaled by their maximum. Values are in the stored conventionnumpy()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
PixelLayerobject- Raises:
TypeError – If the array is not a float,
uint8oruint16numpy.ndarrayValueError – 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
Imageobject to convert to photoshopparent – 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
PixelLayerobject- Raises:
TypeError – If image is not a PIL Image
ValueError – If parent is None
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_modeon 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. Usefromarray()to keep more precision.
ShapeLayer
SmartObjectLayer
- class psd_tools.api.layers.SmartObjectLayer(parent: GroupMixin, record: LayerRecord, channels: ChannelDataList)[source]
Layer that inserts external data.
Use
smart_objectattribute to get the external data. SeeSmartObject.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:
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
textproperty. Styling information for paragraphs is inengine_dict. Document styling information such as font list is isresource_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 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 text_type: TextType | None
Text type. Read-only.
- Returns:
psd_tools.constants.TextType.POINTfor point type text(also known as character type)
psd_tools.constants.TextType.PARAGRAPHfor paragraph type text(also known as area type)
None if text type cannot be determined or information is unavailable
- 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
TypeSettingobject 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_dictfor raw data.