Usage
Command line
The package provides command line tools to handle a PSD document:
psd-tools export <input_file> <output_file> [options]
psd-tools show <input_file> [options]
psd-tools debug <input_file> [options]
psd-tools -h | --help
psd-tools --version
Example:
psd-tools show example.psd # Show the file content
psd-tools export example.psd example.png # Export as PNG
psd-tools export example.psd[0] example-0.png # Export layer as PNG
Working with PSD document
Note
Rendering is bounded by an allocation budget, 4 GiB by default. See Handling untrusted files to change it, and for what it does not bound.
psd_tools.api package provides the user-friendly API to work
with PSD files.
PSDImage represents a PSD file.
Open an image:
from psd_tools import PSDImage
psdimage = PSDImage.open('my_image.psd')
Most of the data structure in the psd-tools suppports pretty
printing in IPython environment.
In [1]: PSDImage.open('example.psd')
Out[1]:
PSDImage(mode=RGB size=101x55 depth=8 channels=3)
[0] PixelLayer('Background' size=101x55)
[1] PixelLayer('Layer 1' size=85x46)
Internal layers are accessible by iterator or indexing:
for layer in psdimage:
print(layer)
if layer.is_group():
for child in layer:
print(child)
child = psdimage[0][0]
Note
The iteration order is from background to foreground, which is
reversed from version prior to 1.7.x. Use reversed(psd) to
iterate from foreground to background.
The opened PSD file can be saved:
psdimage.save('output.psd')
If the PSD File’s layer structure was updated, saving it will update the ImageData section. However, the rendered image is likely different from the Photoshop’s rendering due to the limited rendering support in psd_tools.
Working with Layers
There are various layer kinds in Photoshop.
The most basic layer type is PixelLayer:
print(layer.name)
layer.kind == 'pixel'
Some of the layer attributes are editable, such as a layer name:
layer.name = 'Updated layer 1'
psd_tools experimentally supports the creation of a new PixelLayer from a PIL object, the PIL image will be converted to the color mode of the PSD File given in parameter:
psdimage.create_pixel_layer(pil_image, name="Layer name")
To construct a layered PSD file from scratch:
psdimage = PSDImage.new(mode='RGB', size=(640, 480), depth=8)
group = psdimage.create_group(name="Group 1")
layer = group.create_pixel_layer(pil_image, name="Layer 1", top=0, left=0, opacity=255)
psdimage.save('new_image.psd')
A PIL image carries 8 bits per channel, so a pixel layer in a 16- or 32-bit document keeps more precision only when created from an array:
psdimage.create_pixel_layer_from_array(array, name="Deep layer")
See the function documentation for further parameter explanations.
Group has internal layers:
for layer in group:
print(layer)
first_layer = group[0]
Create a new group object.:
group = psdimage.create_group(name="Group name")
layer = group.create_pixel_layer(pil_image, name="Layer in group")
TypeLayer is a layer with texts:
print(layer.text)
Typographic details such as fonts, character styles, and paragraph styles are
available via the typesetting
property. See typesetting for full API reference:
for paragraph in layer.typesetting:
print(paragraph.style.justification)
for run in paragraph:
print(run.text, run.style.font_name, run.style.font_size)
ShapeLayer draws a vector shape, and the
shape information is stored in vector_mask and origination property.
Other layers can also have shape information as a mask:
print(layer.vector_mask)
for shape in layer.origination:
print(shape)
SmartObjectLayer embeds or links an
external file for non-destructive editing. The file content is accessible
via smart_object property:
import io
so = layer.smart_object
if so.detected_filetype in ('jpg', 'png'):
# External links are read from the current working directory by
# default; pass open(external_dir=...) to point at the directory that
# holds the linked files, or open(trust_full_path=True) for fully
# trusted PSDs to follow the absolute path stored in the file.
with so.open() as f:
image = Image.open(io.BytesIO(f.read()))
SolidColorFill,
PatternFill, and
GradientFill are fill layers that
paint the entire region if there is no associated mask. Sub-classes of
AdjustmentLayer represents layer
adjustment applied to the composed image. See Adjustment layers.
Modifying the layer structure
A layer has at most one parent. PSDImage
and Group hold their child layers in order,
and adding a layer that already has a parent moves it out of that parent rather
than copying it. The internal model of the layer structure is updated
automatically. To bring a layer in from another document, copy it with
copy_to().
The following methods are valid for both PSDImage and Group objects. Besides
indexing, iteration, reversed(), len(), in and del group[i],
they are the only list operations provided: sort(), reverse(), +=,
copy() and slice assignment or deletion are not supported.
Replace the layer at a given index:
group[0] = layer
Add a layer or layers to a group. extend() accepts any iterable, including
another group, whose layers it moves out:
group.append(layer)
group.extend(layers)
group.extend(other_group)
Insert a layer to a specific index in the group:
group.insert(3, layer)
Adding a layer from another document moves it out of that document, and emits a
DeprecationWarning: it will raise ValueError. Copy it
instead:
copy = layer.copy_to(other_psdimage)
copy = layer.copy_to(other_group, index=0)
copy_to() copies the layer or group it is
called on, with its whole subtree, and leaves the source in place. index is
the copy’s position in the destination afterwards, -1 being the top; the
default is the top. The copy:
is converted to the destination’s colour mode, depth and file version. Narrowing, such as 32 to 8 bit, tone-maps as Photoshop’s Image > Mode does, so the copy looks like the source’s
topil(). A layer that cannot be converted to the destination’s colour mode raisesValueError.gets fresh layer IDs.
carries the linked smart objects and the patterns it uses, as independent copies. An ID that clashes with one in the destination is reissued. Patterns keep their own colour mode.
does not bring the layers clipped to it, because clipping depends on position.
A Bitmap, Indexed or Multichannel destination cannot hold layers and raises
ValueError. An Artboard can only be copied
to the document root. Within one document, copy_to() delegates to
duplicate(), but defaults to the top of the
destination rather than directly above the source.
Remove a layer from a group:
group.remove(layer)
Pop a layer from the group:
layer = group.pop()
Emptying a layer group:
group.clear()
Get the index of a layer in the group:
index = group.index(layer)
Check whether a group holds a layer, as 0 or 1:
count = group.count(layer)
Move layers into a newly created group, placed at the top of the group or
document it is created on. layer_list is any iterable, and may be omitted
to create an empty group:
group = psdimage.create_group(layer_list=[layer1, layer2, ...], name="New Group")
Move a layer into another group, or the document root, of the same document. index is
the layer’s position afterwards, -1 being the top, and an index out of range
raises IndexError. The default is the top. Layers clipped to the moved layer
stay behind, because clipping depends on position:
layer.move_to(group)
layer.move_to(group, index=0)
An Artboard can only be moved to the document
root.
Duplicate a layer directly above the original, or into a group in the same document:
copied_layer = layer.duplicate(name="Layer copy")
copied_group = group.duplicate(parent=target_group, index=0)
duplicate() copies a group’s entire
subtree, retaining layer types, pixel data, masks and layer metadata. The
copy gets fresh layer IDs and can be edited independently. Smart-object
contents and other document resources remain shared. The source stays in
place. duplicate() does not cross documents; use copy_to(). A detached
source needs an explicit destination parent. index is the copy’s position in the
destination after the call; -1 is the top. An out-of-range index raises
IndexError. Without it, a copy goes immediately above its source in the
same parent, or to the top of a different container. A copy placed directly
above its source releases the clipped layers above the source, as Photoshop
does. Artboards can only be duplicated at the document root, and the copy
keeps the source’s rectangle, so it overlaps the source; Photoshop moves it
aside. Smart-object copies share the original content but have fresh instance
IDs.
A layer can change its order within its group:
layer.move_up() # Will send the layer upward in the group
layer.move_down() # Will send the layer downward in the group
A layer removed from its document keeps its properties and pixels, can be
composited, and can be added back. move_up(), move_down() and
delete_layer() raise ValueError on it, and on any layer inside a removed
group, because they act on the document’s layer tree.
Every edit above marks the document as edited, so save() regenerates the
flattened preview instead of writing the one the file was opened with. An
edit this API cannot see – reaching past it into a descriptor, a tagged
block or any other low-level record – does not, and has to say so with
mark_updated():
psdimage.mark_updated()
Without it the saved file keeps a preview that disagrees with its own layers, and every reader that trusts the preview, psd-tools included, shows the image from before the edit. The preview is all it marks, though: a wrapper that memoised the record you replaced goes on reporting what it read.
Exporting data to PIL
Export the entire document as PIL.Image:
image = psd.composite()
image.save('exported.png')
Export a single layer including masks and clipping layers:
image = layer.composite()
Export layer and mask separately without composition:
image = layer.topil()
mask = layer.mask.topil()
To composite specific layers, such as layers except for texts, use layer_filter option:
image = psd.composite(
layer_filter=lambda layer: layer.is_visible() and layer.kind != 'type')
Note
Advanced compositing features require optional dependencies. Install with:
pip install psd-tools[composite]
These dependencies (aggdraw, scipy) are needed for:
Vector strokes
Gradient and pattern fills
Layer effects
Basic compositing works without them by using cached previews or simple
pixel-based operations. If a feature requires missing dependencies, an
ImportError with installation instructions will be raised.
Note that most layer effects are not supported. Adjustment layers have limited support (BrightnessContrast, Levels, Curves, Exposure, Invert, Posterize, Threshold). The compositing result may look different from Photoshop.
Note
Color mode caveats when compositing:
Duotone and LAB blending is approximated, and warns when used.
CMYK and LAB images are converted to sRGB through the embedded ICC profile by default. Pass
apply_icc=Falsetocomposite()ortopil()to keep the document’s own colour space. A CMYK document without an embedded profile stays in CMYK, which PNG cannot store; save it as TIFF or JPEG instead.Multichannel documents come back as a single-channel image, because PIL has no multichannel mode and only the first spot channel survives the conversion. Use
psd_tools.composite.composite()to get every channel as a NumPy array.Photoshop discards the layer records when it opens a multichannel document and displays the merged image data, so compositing a multichannel document that has layers does not reproduce what Photoshop shows for the same file. Use
topil()for the merged data.
Exporting data to NumPy
PSDImage or layers can be exported to NumPy array by
numpy() method:
image = psd.numpy()
layer_image = layer.numpy()