Use "Relink to File" button in Photoshop using Python

Issue

I would like to relink a Photoshop Smart Object to a new file using Python.
Here’s a screenshot of the button that’s used in Photoshop to perform this action – "Relink to File":

I’ve found some solutions in other programming languages but couldn’t make them work in Python, here’s one for example: Photoshop Scripting: Relink Smart Object

Editing Contents of a Smart Object would also be a good option, but I can’t seem to figure that one out either.
Here’s a screenshot of the button to Edit Contents of a Smart Object:

So far I have this:

import win32com.client

psApp = win32com.client.Dispatch('Photoshop.Application')
psDoc = psApp.Application.ActiveDocument

for layer in psDoc.layers:
    if layer.kind == 17:  # layer kind 17 is Smart Object
        print(layer.name)
        # here it should either "Relink to File" or "Edit Contents" of a Smart Object

Solution

I have figured out a workaround! I simply ran JavaScript in Python.

This is the code to Relink to File.... You could do a similar thing for Edit Contents but I haven’t tried it yet, as relinking works better for me.

Keep in mind the new_img_path must be a raw string as far as I’m aware, for example:

new_img_path = r"C:\\Users\\miha\\someEpicPic.jpg"

import photoshop.api as ps

def js_relink(new_img_path):
    jscode = r"""
    var desc = new ActionDescriptor();
    desc.putPath(stringIDToTypeID('null'), new File("{}"));
    executeAction(stringIDToTypeID('placedLayerRelinkToFile'), desc, DialogModes.NO);
    """.format(new_img_path)
    JavaScript(jscode)

def JavaScript(js_code):
    app = ps.Application()
    app.doJavaScript(js_code)

Answered By – Miha

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published