SoFunction
Updated on 2024-11-18

Python parsing PSD files via psd-tools

Preface:

Recently encountered business needs based on PSD files to realize the PSD file parsing layer function, searched for a Python parsing PSD library. This library ispsd-toolspsd-toolsis a Python package for processing Adobe Photoshop PSD files. The following arepsd-toolsThe basic introduction.

specificities

Support.

  • Reading and writing primary PSD/PSB file structures
  • Export raw layer images in NumPy and PIL formats

Limited support:

  • Pixel-based construction of basic layers
  • Construction of the fill layer effect
  • Vector Mask
  • Edit some layer properties, such as the layer name
  • Mixing modes other than dissolution
  • Plotting Bezier curves

No support:

  • Editing the layer structure, such as adding or removing a layer
  • Construction of the adjustment layer
  • Construction of many layer effects
  • font rendering

mounting

Use pip to install the package.

pip install psd-tools 

In order to use the full layer image compositing functionality, you can also install NumPy/SciPy.

pip install numpy scipy

utilization

Simple example:

from psd_tools import PSDImage
psd = ('')
().save('')
for layer in psd:
    print(layer)
    layer_image = ()
    layer_image.save('%' % )

1. Command line

This package provides command line tools to work with PSD files.

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   # Display the contents of the file
psd-tools export    # Export as PNG
psd-tools export [0]   # Export layers asPNG

2. Manipulating PSD files

psd_tools.api package provides a user-friendly API to work with PSD files.

Open an image.

from psd_tools import PSDImage
psd = ('my_image.psd')

psd-toolsMost of the data structures in support printing in the IPython environment:

In [1]: ('')
Out[1]:
PSDImage(mode=RGB size=101x55 depth=8 channels=3)
  [0] PixelLayer('Background' size=101x55)
  [1] PixelLayer('Layer 1' size=85x46)

Internal layers can be accessed via iterators or indexes:

for layer in psd:
    print(layer)
    if layer.is_group():
        for child in layer:
            print(child)

child = psd[0][0]

Opened PSD files can be saved as.

('')

3. Operational use layer

In Photoshop, there are various kinds of layers.

The most basic layer types arePixelLayer:

print()
 == 'pixel'

Some layer properties are editable, e.g. Layer Name.

 = 'Updated layer 1'

There are internal layers in the group.

for layer in group:
    print(layer)
first_layer = group[0]

TypeLayer is a layer with the text.

print()

ShapeLayer Draws a vector shape with shape information stored in the vector_mask and origination attributes. Other layers can also have shape information as masks: the

print(layer.vector_mask)
for shape in :
    print(shape)

SmartObjectLayer Embed or link an external file for non-destructive editing. The contents of the file can be accessed via the smart_object attribute:.

import io
if layer.smart_object.filetype in ('jpg', 'png'):
    image = ((layer.smart_object.data))

SolidColorFillPatternFill, andGradientFill are fill layers that draw the entire area if there is no associated mask.AdjustmentLayer subclasses represent the layer adjustments applied to the constituent images. See also theAdjustment layers.

4. Exporting data to PIL

Export the entire file as:

image = ()
('')

Export a single layer, including masks and clipping layers.

image = ()

Export layers and masks separately, without compositing: the

image = ()
mask = ()

To composite a specific layer, such as a layer other than text, use the layer_filter option:.

image = (
    layer_filter=lambda layer: layer.is_visible() and  != 'type')

Please note:Most layer effects and adjustment layers are not supported. Compositing results may look different from Photoshop.

4. Exporting data to NumPy

PSDImage or layers can be accessed via thenumpy() method exports to a NumPy array: the

image = ()
layer_image = ()

More Operations

1. Manipulating a PSD file

The PSDImage class can be seen in psd_image.py in the source code

1. Open a file

from psd_tools import PSDImage
psd = ('my_image.psd')
# Returns an object of type PSDImage

Most of the data structures in #psd_tools support pretty printing in the IPython environment.

#  In [1]: ('')
#  Out[1]:
#  PSDImage(mode=RGB size=101x55 depth=8 channels=3)
#    [0] PixelLayer('Background' size=101x55)
#    [1] PixelLayer('Layer 1' size=85x46)

2. psd's properties (PSDImage class can be seen in psd_image.py in the source code)

Some meaningless attributes are also defined, in order to be the same as layer can be, such as: visible directly return Ture.

Here's a list of some of the attributes that make sense and are generally used:

 #Broad
 #High
 #(width, height) tuple
 #(left, top) tuple
 #0
 #
 #0
 #
 #(left, top, right, bottom) `tuple`

 # The smallest box (x,y,z,w) that encloses all visible layers.
psd.color_mode # Color modes such as RGB, GRAYSCALE
 # of color channels
 # of pixel depth bits
 # file version psd is 1, psb is 2.
psd.has_preview #Returns if the document has real merged data. When True, `topil()`returns pre-composed data.
psd.has_thumbnail #With or without thumbnails
 #come (or go) back    Thumbnails in the format

Here's a list of some meaningless attributes that are meant to be manipulated in the same way as layers:

psd.is_visible() #True
 #True
 #None
   #'Root'
 #'psdimage'

print(str(psd.is_group()))# Is it a group psd file passed in directly is also a group
psdThe layers of the file can be traversed:
for layer in psd:
print(layer)
if layer.is_group():
    for child in layer:
        print(child)

child = psd[0][0]
#The iteration order is from background to foreground,together with1.Previous versions to the contrary。utilizationreverse (list(psd))Iterate from front to back。

3. Save psd file

('')

4. Obtain a PIL image from a psd file.

(channel=None, **kwargs)
#channel:0because ofR,1because ofG,2because ofB,-1because ofA,according toChannelIDresemble。

5. Merge psd files.

(force = False,bbox=None,**kwargs)

6. Using PIL Image to generate a PSDImage object

from psd_tools import PSDImage
psd = (image,compression=<Compression.PACK_BITS: 1>)

2. Manipulating a PSD layer

You can see the Layer class in the source code.

attribute (see the Layer class in the source code).

 # Name of layer (writable)
 #Layer categories (strings)

#(group(layer group), pixel(ordinary layer (computing)), shape, type(Text Layer), smartobject,or psdimage(psdin itself))
The #shape draws vector shapes, with shape information stored in the vector_mask and origination attributes. Other layers can also have shape information as masks: the
#smartobject embeds or links external files for non-destructive editing. The contents of the file can be accessed via the smart_object attribute.

layer.layer_id #Layer ID.
 Whether or not the # layer itself is checked to be visible (writable)
layer.is_visible() Whether a # layer is visible or not is affected by the parent object. (If the parent object is not visible, this layer will be False even if this is checked as visible)

 #Transparency [0,255] (writable)
 #Parent of this layer.
layer.is_group # Is it a group
layer.blend_mode # BlendMode (writable), BlendMode in return
layer.has_mask #Whether there is a mask
 # Left coordinate (writable)
  # top coordinates (writable)
 # Right coordinate
 #Bottom coordinates
 Width of layer #
 #high
 #(left, top) tuple. (writable)
 #(width, height) tuple.
 #(left, top, right, bottom) tuple.
layer.has_pixels() #Whether there are pixels
layer.has_mask() # Is there a mask
layer.has_vector_mask() #With or without vector masks
 #Layer related masks return: :py:class:`~psd_tools.` or `None`
layer.vector_mask #Layer-associated vector mask return: :py:class:`~psd_tools.` or `None`
layer.has_origination() #Whether there is a real-time shape attribute
 # Real-time shape properties
layer.has_stroke() # Is there a comparison
 #Compare
layer.has_clip_layers() # With or without cropping
layer.clip_layers #crop,Clip layers associated with this layer.
layer.has_effects() # Are effect treatments
 #Effects processing return: :py:class:`~psd_tools.`
layer.tagged_blocks #Layer tagged blocks that is a dict-like container of settings.

2. Get PIL Image of the layer. (Returns object or `None` if no pixels are present.)

(channel=None, **kwargs)
.
from psd_tools.constants import ChannelID
image = ()
red = (ChannelID.CHANNEL_0)
alpha = (ChannelID.TRANSPARENCY_MASK)

3. Merge layers and their masks (mask, vector mask, and clipping layers) (returns `None` for objects or no pixels).

(bbox=None, **kwargs)

Not merged, obtained separately:

image = ()
mask = ()
from psd_tools import compose
clip_image = compose(layer.clip_layers)

This article on Python psd files through psd-tools parsing PSD files to this article, more related Python PSD content, please search my previous posts or continue to browse the following related articles I hope that you will support me more in the future!