lohriialo / photoshop-scripting-python

Scripting in Photoshop is used to automate a wide variety of repetitive task or as complex as an entire new feature
485 stars 95 forks source link

How to use python to get all the layer information in a psd file? #13

Open zhenzi0322 opened 3 years ago

oh-ok commented 1 year ago

Goes without saying that this depends entirely what properties you're looking to get, but here's a good start. You can run this as a script with the files as command-line arguments.

Windows

import sys
from os.path import abspath
# Pretty printing, so that the result is legible
from pprint import pprint
from win32com.client import Dispatch

ps = Dispatch("Photoshop.Application")

# Add/remove any properties you want returned here
def parse_layer(lyr):
    return {
        "name": lyr.Name,
        "opacity": lyr.Opacity,
        "blend mode": lyr.BlendMode,
        "bounds": lyr.Bounds
    }

def get_layer_info(parent):
    result = []
    for i in range(1, parent.Layers.Count+1): # 1-based index
        curlyr = parent.Layers.Item(i)
        info = parse_layer(curlyr)
        # If it's a LayerSet, then run this again with the LayerSet as the parent
        if curlyr.typename == "LayerSet":
            info["items"] = get_layer_info(curlyr)
        result.append(info)
    return result

# Reference files you want to inspect as command-line arguments
for file in sys.argv[1:]:
    print(f"Info for: {file}")
    cur_doc = ps.Open(abspath(file))
    pprint(
        get_layer_info(cur_doc),
        sort_dicts=False
    )
    cur_doc.Close(2)

macOS

import sys
from os.path import abspath
# Pretty printing, so that the result is legible
from pprint import pprint
from appscript import app, k

ps = app(id="com.adobe.Photoshop", terms="sdef")

def get_layer_info(parent):
    # appscript lets us return all the layer's properties in one command
    props = parent.layers.properties()
    for i, info in enumerate(props):
        # If it's a LayerSet, then run this again with the LayerSet as the parent
        if info[k.class_] == k.layer_set:
            info[k.layers] = get_layer_info(parent.layers[i+1]) # 1-based index
    return props

# Reference files you want to inspect as command-line arguments
for file in sys.argv[1:]:
    print(f"Info for: {file}")
    ps.open(abspath(file))
    pprint(
        get_layer_info(ps.current_document),
        sort_dicts=False
    )
    ps.current_document.close(saving=k.no)