psd_tools
See Usage for examples.
PSDImage
- class psd_tools.PSDImage(data: PSD)[source]
Photoshop PSD/PSB document.
The low-level data structure is accessible at
PSDImage._record.Example:
from psd_tools import PSDImage psdimage = PSDImage.open('example.psd') image = psdimage.composite() for layer in psdimage: layer_image = layer.composite()
- append(layer: Layer) None
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 artboards: list[Artboard]
Top-level artboards in z-order, bottom first.
Artboards nested in other groups are not included; use
descendants()for those.
- property background_color: float | tuple[float, ...] | None
Background color for the merged composite image. Writable.
When set,
save()composites layers against an opaque backdrop of this color instead of a transparent one.Values are in [0.0, 1.0] range, matching the
composite()colorparameter:RGB / Grayscale:
1.0= white,0.0= blackCMYK:
(1.0, 1.0, 1.0, 1.0)= white,(1.0, 1.0, 1.0, 0.0)= black. Values count the ink left, so 1.0 is no ink, as in thecolorparameter andnumpy().
Use a scalar for uniform color or a tuple for per-channel values. Set to
Nonefor a transparent backdrop.new()sets it from thecolorparameter.- Returns:
float, tuple[float, …], or None
Example:
psd = PSDImage.new('RGB', (640, 480), color=1.0) psd.save('output.psd') # White background, 3 channels (no alpha)
- property bbox: tuple[int, int, int, int]
Minimal bounding box that contains all the visible layers.
Use
viewboxto get viewport bounding box. When the psd is empty, bbox is equal to the canvas bounding box.- Returns:
(left, top, right, bottom) tuple.
- clear() None
Clear the group.
This operation rewrites the internal references of the layers.
- Returns:
None
- property color_mode: ColorMode
Document color mode, such as ‘RGB’ or ‘GRAYSCALE’.
See
ColorMode.- Returns:
- property compatibility_mode: CompatibilityMode
Set the compositing and layer organization compatibility mode. Writable.
This property checks whether the PSD file is compatible with specific authoring tools, such as Photoshop or CLIP Studio Paint. Different authoring tools may have different ways of handling layers, such as the use of clipping masks for groups. Default is Photoshop compatibility mode.
- Returns:
- composite(viewport: tuple[int, int, int, int] | None = None, force: bool = False, color: float | Sequence[float] | ndarray | None = 1.0, alpha: float | ndarray = 0.0, layer_filter: Callable | None = None, ignore_preview: bool = False, apply_icc: bool = True) Image[source]
Composite the PSD image.
The result spans the whole canvas. For a document with artboards that is not any single design; use
composite()for one artboard.- Parameters:
viewport – Viewport bounding box specified by (x1, y1, x2, y2) tuple. Default is the viewbox of the PSD.
ignore_preview – Boolean flag to whether skip compositing when a pre-composited preview is available.
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().
- Returns:
PIL.Image.
- count(layer: Layer) int
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
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
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
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]
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
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
Return the first layer found for the given layer name.
- Parameters:
name
- findall(name: str) Iterator[Layer]
Return a generator to iterate over all layers with the given name.
- Parameters:
name
- classmethod fromarray(array: ndarray, mode: str | None = None, depth: Literal[1, 8, 16, 32] | None = None, compression: Compression = Compression.RLE, color: int | float | Sequence[int | float] | None = None) Self[source]
Create a new layer-less PSD document from a NumPy array.
The inverse of
toarray(): the array is stored at the document’s depth, in the conventiontoarray()returns, so a CMYK array holds 255 for no ink. In RGB and grayscale modes with a transparency channel the colour is stored composited over white, as in the merged preview, so colour under transparent pixels does not survivetoarray().- Parameters:
array –
(height, width, channels)array, or(height, width)for a single channel.channelsis the mode’s colour channel count, with one more for transparency whenmodeends inA. Floating point values are in [0, 1];uint8anduint16are scaled by their maximum.mode – PIL-style mode such as
"RGB","RGBA"or"CMYK". Defaults to"L","RGB"or"RGBA"by channel count.depth – Bit depth. Defaults to 1 for mode
"1", otherwise 8 foruint8, 16 foruint16and 32 for floating point.compression – ImageData compression option.
color – Background color, as in
frompil().
- Returns:
A
PSDImageobject.- Raises:
TypeError – If the array is not a float,
uint8oruint16numpy.ndarray.ValueError – If the array is empty, non-finite, or of the wrong shape for the mode, or the mode is indexed.
- classmethod frompil(image: Image, compression: Compression = Compression.RLE, color: int | float | Sequence[int | float] | None = None) Self[source]
Create a new layer-less PSD document from PIL Image.
- Parameters:
image – PIL Image object.
compression – ImageData compression option. See
Compression.color – Background color for the compositing backdrop when saving. Accepts the same types as
new()color. When set,save()will composite layers against an opaque backdrop of this color.
- Returns:
A
PSDImageobject.
- has_preview() bool[source]
Whether the document has real merged data.
When True, topil() returns pre-composed data.
- property image_resources: ImageResources
Document image resources.
A dict-like structure of document settings. See
psd_tools.constants.Resourcefor available keys.- Returns:
Example:
from psd_tools.constants import Resource version_info = psd.image_resources.get_data(Resource.VERSION_INFO) slices = psd.image_resources.get_data(Resource.SLICES)
To export a TIFF file, which holds any color mode, with the embedded ICC profile:
from psd_tools.constants import Resource icc_profile = psd.image_resources.get_data(Resource.ICC_PROFILE) image = psd.composite(apply_icc=False) image.save('output.tif', icc_profile=icc_profile)
- index(layer: Layer) int
Return the index of the specified layer in the group.
- Parameters:
layer – The layer to find.
- insert(index: int, layer: Layer) None
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_updated() bool[source]
Return whether the document has been edited.
See
mark_updated()for what sets this and what it gates.- Returns:
bool
- mark_updated() None[source]
Mark the document’s stored preview as stale.
While marked,
save()regenerates the flattened preview from the layers,composite()re-renders instead of returning the stored preview, andLayer.composite()redraws vectors instead of using a layer’s stored pixels.Call this after an edit this API cannot see, such as one through an effect’s
descriptor, a layer’stagged_blocks, or any other low-level record. Most edits made through this API set it themselves.It marks the preview only. Wrappers that memoise on first access (
mask,vector_mask,origination,stroke, smart object and typesetting), the_dataof an adjustment or fill layer, and a group’s bbox keep the record they read.Nothing clears the flag,
save()included. It lives on thePSDImage, so reach it there rather than throughLayer.parent.
- property max_alloc_bytes: int | Literal['unlimited'] | None
Allocation budget for this document and its layers.
A positive int is a byte ceiling on each estimated allocation, and
"unlimited"disables it.None, the default, defers topsd_tools.api.utils.MAX_ALLOC_BYTESwhenever the budget is checked. Gives the setting, not the resolved ceiling; usepsd_tools.api.utils.resolve_alloc_budget()for that. See Handling untrusted files.- Raises:
TypeError – on assigning a bool or a value that is not an int, a string or
None.ValueError – on assigning a non-positive int or a string other than
"unlimited".
- classmethod new(mode: str, size: tuple[int, int], color: int | float | Sequence[int | float] = 0, depth: Literal[1, 8, 16, 32] | None = None, **kwargs: Any) Self[source]
Create a new PSD document.
- Parameters:
mode – The color mode to use for the new image.
size – A tuple containing (width, height) in pixels.
color – What color to use for the image. Default is black. Accepts a single integer (0-255 for 8-bit, 0 or 1 at depth 1) or float in the [0.0, 1.0] range, or a sequence of per-channel values using the same ranges (e.g., 3 values for
"RGB", 4 for"CMYK"). Mixed int/float sequences are allowed. The color is used both as the initial image data fill and as thebackground_colorcompositing backdrop when saving.depth – Bit depth, or
Noneto select 1 for mode"1"and 8 otherwise. Mode"1"accepts only 1; every other mode accepts 8, 16 or 32.
- Returns:
A
PSDImageobject.
Note
A
depth=32document carries the defaulthdrt(HDR toning) block in its color mode data, which Photoshop requires of every 32-bit file (#869).
- numpy(channel: Literal['color', 'shape', 'alpha', 'mask'] | None = None) ndarray
Get NumPy array of the document.
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’.
- Returns:
- classmethod open(fp: IO[bytes] | str | bytes | PathLike, max_alloc_bytes: int | Literal['unlimited'] | None = None, parse_limits: ParseLimits | None = None, **kwargs: Any) Self[source]
Open a PSD document.
- Parameters:
fp – filename or file-like object.
parse_limits – structural read and object limits;
NoneusesParseLimitsdefaults. Exceeding a limit raisesParseLimitErrorbefore the allocation.max_alloc_bytes – initial
max_alloc_bytes, checked before the file is read. Caps (bytes) whatcomposite()/numpy()/topil()/thumbnail()allocate; rendering raisesValueError, or skips a layer effect, if the estimate exceeds it.numpy()andtopil()estimate their allocation at its peak, intermediates included, so the estimate depends on the colour mode, the depth and the compression method rather than on the declared geometry alone.Layer.numpy()andLayer.topil()apply the same ceiling to each layer read, at the layer’s own size, andcomposite()to each stroke or pattern canvas that a descriptor’s size grows. A layer effect over the ceiling is skipped rather than raising; a vector stroke or a fill layer over it raisesValueError.composite()bounds the canvas it builds instead, from the geometry: what follows that guard grows with the layer count, which no such estimate can bound. Note thatcomposite()reaches the other two in the ordinary cases – it returns the preview throughtopil()when the document has one, and a document with no layers falls through tonumpy(). See Handling untrusted files for the precedence and what it does not bound.encoding – charset encoding of the pascal string within the file, default ‘macroman’. Some psd files need explicit encoding option.
- Returns:
A
PSDImageobject.- Raises:
TypeError – if
max_alloc_bytesis not an int, a string orNone, or is a bool.ValueError – if
max_alloc_bytesis not positive or is a string other than"unlimited".
- pop(index: int = -1) Layer
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
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
- save(fp: IO[bytes] | str | bytes | PathLike, mode: str = 'wb', **kwargs: Any) None[source]
Save the PSD file. Updates the ImageData section if the document has been edited.
- Parameters:
fp – filename or file-like object.
encoding – charset encoding of the pascal string within the file, default ‘macroman’.
mode – file open mode, default ‘wb’.
- property tagged_blocks: TaggedBlocks | None
Document tagged blocks that is a dict-like container of settings.
See
psd_tools.constants.Tagfor available keys.- Returns:
TaggedBlocksor None.
Example:
from psd_tools.constants import Tag patterns = psd.tagged_blocks.get_data(Tag.PATTERNS1)
- thumbnail() Image | None[source]
Return a thumbnail image in PIL.Image.
Gives None when the file contains no embedded thumbnail image.
- Raises:
ValueError – if the thumbnail’s dimensions exceed the PSD spec limit, or
max_alloc_bytes.
- toarray(channel: Literal['color', 'shape', 'alpha', 'mask'] | None = None) ndarray[source]
Get NumPy array of the document.
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’.
- Returns:
- topil(channel: int | ChannelID | None = None, apply_icc: bool = True) Image | None[source]
Get PIL Image.
- 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, or None if the composed image is not available.
Parsing limits
Warnings
- class psd_tools.PSDDecompressionWarning[source]
Issued when channel data cannot be fully decompressed.
The affected channel is replaced with black pixels, at every depth –
lengthbytes of whichever value that depth spells black as, zero from depth 8 up and0xffat depth 1, where an inked pixel is a set bit. Catch or filter this warning to detect silently degraded images:import warnings from psd_tools.compression import PSDDecompressionWarning with warnings.catch_warnings(): warnings.simplefilter("error", PSDDecompressionWarning) psd = PSDImage.open("file.psd")