Replace the image on a smart object layer without opening photoshop using python
21:19 02 Jul 2023

I would like to open a template file such as "shirt_mockup.psd" and replace the image on a given layer such as "replacement_layer" to produce a mockup like "mockup.png". While this is easy in Photoshop, a better method is needed to process a large number of images for the same template in my application. It's also necessary to do this without opening Photoshop

Attempts: psd-tools library is good but non-writable (as far as I can tell). photoshop_python_api library appears very complex and seems to depend on winreg for python2, while I'm using python3 in my application. Open to alternative approaches for automating the mockups from a template!

Pseudocode:

from psd_tools import PSDImage
from PIL import Image

def insert_image_into_psd(psd_file, layer_name, insert_image_file, output_file):
    psd = PSDImage.open(psd_file)

    for l in psd:
        if l.name == layer_name:
            insert_image = Image.open(insert_image_file).convert("RGBA")
            resized_image = insert_image.resize(l.size, resample=Image.LANCZOS)
            l.topil().paste(resized_image, box=(0, 0))
            break

    psd.save(output_file)
    psd.composite().save(output_file + ".png")
    print("Image inserted into the specified layer and saved as PSD and PNG.")

psd_file = "template.psd"
layer_name = "your design here - doubleclick on thumnail"
insert_image_file = "replacement.png"
output_file = "output.psd"

insert_image_into_psd(psd_file, layer_name, insert_image_file, output_file)
python python-3.x image-processing python-imaging-library photoshop