Highlighted

Photoshop script. Replace layers from another opened document.

Community Beginner ,
Sep 09, 2020

Copy link to clipboard

Copied

Hi all!
I am starting with Photoshop scripting and I am not sure if the functionality I want to achieve is possible or not. It would be awesome if an experienced user could take a look and confirm, and if so, point me in the direction.

Basically I want to replace the layer "LayerA.001" in the targetDocument with the layer "LayerA.002" contained in the sourceDocument.psd, and so on with LayerB.001, C.001, D.001...
Now I can copy layers from one document to another but I can't locate specific layers by name using wildcards and replace them.
The targetDocument.psd contains a real scenario case(layers are duplicated, contained nested groups, clipped adjustment layers..) and the sourceDocument.psd contains the updated versions of these layers to be updated.
I understand that both documents must be open simultaneously, and one of both specifically must be in focus to work. Also, as HardMode, ti would be fantastic to keep the new name in replaced layers (in this sample xxxxx.002).

I provided the two sample files. My photoshop is CS6, I know is quite old, but works for our purposes. 

Thank you very much, in advance for the help!!

Here is some code to help identify the Layers in two open files that have the same names except for numbers after a dot at the end of the Layer’s name. 

 

// 2020, use it at your own risk;
var theRegExp = /(.*)\.[^\.]+$/;
// do stuff;
if (app.documents.length == 2) {
var theDocs = app.documents;
var theTarget = app.activeDocument;
if (theDocs[0] == theTarget) {var theSource = theDocs[1]}
else {var theSource = theDocs[0]};
// get layers;
var theTargetLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theSource;
var theSourceLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theTarget;
// process the layers;
var theResults = new Array;
for (var m = 0; m < theTargetLayers.length; m++) {
    if (theTargetLayers[m][0].indexOf(".")!=-1) {var targetName = theTargetLayers[m][0].match(theRegExp)[1]}
    else {var targetName = theTargetLayers[m][0]};
    for (var n = 0; n < theSourceLayers.length; n++) {
        if (theSourceLayers[n][0].indexOf(".")!=-1) {var sourceName = theSourceLayers[n][0].match(theRegExp)[1]}
        else {var sourceName = theSourceLayers[n][0]};
        if (targetName == sourceName) {
            theResults.push([theTargetLayers[m], theSourceLayers[n]])
        }
    }
};
alert ("the corresponding layers are\n"+theResults.join("\n"));
};
////// collect layers //////
function collectLayersNamesIndexAndIdentifier () {
// the file;
var myDocument = app.activeDocument;
// get number of layers;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID('property'), stringIDToTypeID('numberOfLayers'));
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
var applicationDesc = executeActionGet(ref);
var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
var theLayers = new Array;
for (var m = 0; m <= theNumber; m++) {
try {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), m);
var layerDesc = executeActionGet(ref);
var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
var theKind = layerDesc.getInteger(stringIDToTypeID("layerKind"));
// if group collect values;
if (layerSet != "layerSectionEnd" && layerSet != "layerSectionStart" && isBackground != true) {
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
var theIndex = layerDesc.getInteger(stringIDToTypeID('itemIndex'));
theLayers.push([theName, theIndex, theID, theKind])
};
}
catch (e) {};
};
return theLayers
};

 

 

TOPICS
Actions and scripting, How to, Windows

Views

150

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Photoshop script. Replace layers from another opened document.

Community Beginner ,
Sep 09, 2020

Copy link to clipboard

Copied

Hi all!
I am starting with Photoshop scripting and I am not sure if the functionality I want to achieve is possible or not. It would be awesome if an experienced user could take a look and confirm, and if so, point me in the direction.

Basically I want to replace the layer "LayerA.001" in the targetDocument with the layer "LayerA.002" contained in the sourceDocument.psd, and so on with LayerB.001, C.001, D.001...
Now I can copy layers from one document to another but I can't locate specific layers by name using wildcards and replace them.
The targetDocument.psd contains a real scenario case(layers are duplicated, contained nested groups, clipped adjustment layers..) and the sourceDocument.psd contains the updated versions of these layers to be updated.
I understand that both documents must be open simultaneously, and one of both specifically must be in focus to work. Also, as HardMode, ti would be fantastic to keep the new name in replaced layers (in this sample xxxxx.002).

I provided the two sample files. My photoshop is CS6, I know is quite old, but works for our purposes. 

Thank you very much, in advance for the help!!

Here is some code to help identify the Layers in two open files that have the same names except for numbers after a dot at the end of the Layer’s name. 

 

// 2020, use it at your own risk;
var theRegExp = /(.*)\.[^\.]+$/;
// do stuff;
if (app.documents.length == 2) {
var theDocs = app.documents;
var theTarget = app.activeDocument;
if (theDocs[0] == theTarget) {var theSource = theDocs[1]}
else {var theSource = theDocs[0]};
// get layers;
var theTargetLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theSource;
var theSourceLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theTarget;
// process the layers;
var theResults = new Array;
for (var m = 0; m < theTargetLayers.length; m++) {
    if (theTargetLayers[m][0].indexOf(".")!=-1) {var targetName = theTargetLayers[m][0].match(theRegExp)[1]}
    else {var targetName = theTargetLayers[m][0]};
    for (var n = 0; n < theSourceLayers.length; n++) {
        if (theSourceLayers[n][0].indexOf(".")!=-1) {var sourceName = theSourceLayers[n][0].match(theRegExp)[1]}
        else {var sourceName = theSourceLayers[n][0]};
        if (targetName == sourceName) {
            theResults.push([theTargetLayers[m], theSourceLayers[n]])
        }
    }
};
alert ("the corresponding layers are\n"+theResults.join("\n"));
};
////// collect layers //////
function collectLayersNamesIndexAndIdentifier () {
// the file;
var myDocument = app.activeDocument;
// get number of layers;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID('property'), stringIDToTypeID('numberOfLayers'));
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
var applicationDesc = executeActionGet(ref);
var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
var theLayers = new Array;
for (var m = 0; m <= theNumber; m++) {
try {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), m);
var layerDesc = executeActionGet(ref);
var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
var theKind = layerDesc.getInteger(stringIDToTypeID("layerKind"));
// if group collect values;
if (layerSet != "layerSectionEnd" && layerSet != "layerSectionStart" && isBackground != true) {
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
var theIndex = layerDesc.getInteger(stringIDToTypeID('itemIndex'));
theLayers.push([theName, theIndex, theID, theKind])
};
}
catch (e) {};
};
return theLayers
};

 

 

TOPICS
Actions and scripting, How to, Windows

Views

151

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Sep 09, 2020 0
LEGEND ,
Sep 09, 2020

Copy link to clipboard

Copied

That sounds like a task best performed with Smart Objects, possibly even linked Smart Objects. 

Did Photoshop CS6 have those? 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 09, 2020 0
LEGEND ,
Sep 09, 2020

Copy link to clipboard

Copied

»TargetDocument.psd« seems to contain several Layers that are copies of the Layers in question. 

In my opinion those should usually all be Smart Object instances and not independet Layers – or is there a particular reason for this? 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 09, 2020 0
Community Beginner ,
Sep 09, 2020

Copy link to clipboard

Copied

Thank you very much for your fast answer. Photoshop CS6 does have SmartObjects, but not LinkedSmartObjects.
You are completely right, the copy of a layer should be a copy of a smart object actually. The reason behind this is we work in a fast-pace iterations, where a certain update version might be live for a few hours only. That develop on us the bad habit of not creating smart-objects and just replace the layer (which we never modifiy as a non-destructive workflow). Also the chance of finding a copy of a layer in our files is low, but still exists, that is why I made it in the demo files.
For the love of simplicity, it would be good enough if I can replace a normal layer by name with wildcards. However, if it is better or simplier to use smartobjects, that is fine too.
Thank you!!

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 09, 2020 0
Most Valuable Participant ,
Sep 09, 2020

Copy link to clipboard

Copied

I started scripting places smart object layers in CS2 so CS6 has smart object layers.  Replacing Smart object content can be very difficult.  Normal images can have their pixels changed by normals Photoshop tools but the only tool I know the will replace one image with and other is the clone stamp tool  and you really do not want to try to use tool recording.  IMO that feature was never implemented well it full of problems.  You better off deleting the layer you want replaced and pasting in the layer you want. 

 

Getting back to smart Object layers.  Why is it difficult to replace a smart objects layers object after all Photoshop has a such a feature menu Layer>Smart Objects>Replace Contents.   Heck its easy to replace a smart object layer content. Yes it is.  The rub is will that have the desired results. The answer is sometimes it may.

 

Let me explain a little more Photoshop will have no problem replacing a smart object layers content with the content of any support file type you choose  that has any size. Is that what you want? It may be or may not be.  And if it is what you want will it be like you want.   Its a complex issue.   If the the Smart object layer is in a template of some kind like a collage or product.  In general you do not want the object replaces with any odd size object.  For the Smart object layer is being used in a very specific output composite and is probably masked to  a specific are in the composite and the object should be sized for the area.   So when it comes to Templates Replacement should or must be the same size as the object in the template.  If replace the object in the template with a different size object you have most likely broken the template if you save it with the wrong size replacement in the template.

 

An other thing about a smart object layer is the object pixels are set in concrete and are not the pixels in the documents smart object layer.  A transformation of the object pixels are the actual layers pixels that may include warping the user added to the transform the subject matter for the document composite. This is not a destructive transform like on a normal layer. The transform is recorded for the object into the layer and can be edited the user. The transforming will always be fro the hardened objects pixels.

 

So even if you want to replace a small mouse with a large big fat rat if the mouse was was being positioned and warped for the original compost will the warping and position of the rat be what you want. When you replace the content of a smarts object layer how would Photoshop know how you would want the position and warping changed in the layers recorded transform for this different sized object.

 

Replacing a smart object is not simply menu layer>Smart Objects>Replace content.

 

Editing the Smart object you can fit the replacement into the original object canvas and not change its size just update the original object with new content.. However there is a run there too. Not all objects are Photoshop object. Photoshop does not support Camera Raw file Object and Vector Objects. These object will open is ACR or AI your script will loose control of the process and not be able to edit these Smart object. Photoshop script can nor Edit smart objects that are Vector and Camera RAW objects.

 

In general I think you would want document toe be independent therefore embedded smart objects  Linked object I think would be more business related  where you want to keep your logo or something updated everywhere,  Still the linked object process is not Automated.  You need to open assets with link object in Photoshop for Photoshop to update the objects. If you do not open the document in Photoshop they still contains your old content.  So you need to book keep what is used where so when you updated your logo  you know which assets need to be opened so they get updated.

JJMack

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 09, 2020 0
LEGEND ,
Sep 10, 2020

Copy link to clipboard

Copied

»that is why I made it in the demo files.«

In my opinion it is commendable that you tried to create demo-files at all but as they contain empty Layers they can not be the basis for meaningful testing. 

 

»The reason behind this is we work in a fast-pace iterations, where a certain update version might be live for a few hours only. That develop on us the bad habit of not creating smart-objects and just replace the layer (which we never modifiy as a non-destructive workflow).«

Even with Embedded Smart Objects »Replace Contents« allows for quick change of content in an image (if the old and new SO content have the same dimensions and sizes at least); switching in the content as plain pixel layers manually instead seems wasteful to me and not something I would recommend in the least. 

 

»For the love of simplicity, it would be good enough if I can replace a normal layer by name withwildcards.«

That (involving plain pixel layers) does not seem like »simplicity« but like unnecessarily complicating the matter. 

What exactly do you mean by »wildcard« in the name/s, though? Could you please give examples? 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 0
Community Beginner ,
Sep 10, 2020

Copy link to clipboard

Copied

Thank you very much c.pfaffenbichler and JJMack for taking the time to explain in great detail.

<<In my opinion it is commendable that you tried to create demo-files at all but as they contain empty Layers they can not be the basis for meaningful testing. >>
That makes sense. I did empty layers to make smaller files. I thought the content of the layers is irrelevant since the old layers to be replaced have always the same properties than the new ones (resolution, color profile...) since they are new iterations of rendered images. But I missed to provide that information, so I understand it might be misleading, sorry for that. 

<<Even with Embedded Smart Objects »Replace Contents« allows for quick change of content in an image (if the old and new SO content have the same dimensions and sizes at least); switching in the content as plain pixel layers manually instead seems wasteful to me and not something I would recommend in the least. >>
The reason behind is this: Replace contents works fine when the new content is a single image file (logo005.png) but in our workflow, the new layers are contained in an EXR layered file. That is why I am looking for replacing layers from one open document to another. If I select an EXR file as source file to replace content, Photoshop will take all layers inside the file. As far as I know, Photoshop scripting can't handle layered EXRs. By the way, we installed "EXR-IO" in order to handle layered exr files.

<<What exactly do you mean by »wildcard« in the name/s, though? Could you please give examples? >>
The old layer to be replaced can be named "RGBA.0000.001" or "RGBA.0100.005". Same thing with the new updated layer. The digits are changing, but not the prefix. I can't find the way to use wildcards with the method .getByName().

<<Are there only going to be the two images open or do they have to be identified? >>
Yes, there will be only two documents opened. The .psd file containing many layers, including some rendered layers to be replaced, and the other document is the .exr file with the new layers.

<<What is the naming convention identifying the two corresponding files? >>
The two documents don't share the same convention. The psd file is named after the motiv inside by the criteria of the artist working on it ("03 Street perspective 004.psd") . The render exr file is named numerically according to the iteration (001.exr, 002.exr, 007.exr...)

I added a sketch about what is the goal of this script.
Thank you!!

Sample.jpg

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 0
LEGEND ,
Sep 10, 2020

Copy link to clipboard

Copied

Smart Objects 

Smart Objects 

Smart Objects 

 

Duplicating Layers seems much too risky to me – Clipping Mask status, Blend Mode, Fill, Opacity, Layer Style, … of the Layer that is to be replaced would all have to be processed in some manner to assure the intended appearance is maintained. 

Therefore converting the Layer in the source file to a SO, exporting its Contents and then replacing the corresponding SO’s contents in the target document seems to me the only halfway reasonable approach in this situation. 

Added bonus: All the instances of the SO would update where now there are independent »… copy«-layers that would have to be handled separately. 

 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 0
Most Valuable Participant ,
Sep 10, 2020

Copy link to clipboard

Copied

If  you installed Exr-IO to support layered exr files the plug-in will most likely have an import type dialog like some of Photoshop file extension support . Like for  vector file like .esp none Photoshop .PDF etc. There is a additional dialog  when these files are open into photoshop.  They do not open straight into photoshop. So it would not be easy to use scripting with your exr files.  I do not support or allow exr files to be used as replacement image in my collage and mockup scripts because Adobe openExr support more or less has an import dialog in addition to Adobe Photoshop open dialog.

 

 But if you look at a smart object layer in a document though its object may be layered the smart object layer in the document is a single raster layer no vectors in Photoshop even for vector smart objects.. Though vector objects will be scaled with vector graphics there are no vectors in Photoshop they are in the object's file.  So in practice smart object layer have harden pixels for the layer's object and there is a recorded transform that generated the layer pixels from these hardened object's pixels.  Its a raster pixel layer.     You could use flat image files saved from your Layered EXR  documents as replacement content for populating your templates. Replacement could also be saved layered PSD files. That can open and work on in Photoshop.  They just can not be a file type that photoshop does not have native file support for. 

JJMack

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 1
LEGEND ,
Sep 10, 2020

Copy link to clipboard

Copied

The screenshot seems to raise additional questions. 

 

To make sure: What is the source and what the target image? 

Why are the »arrowed« Layers on the right side not numbered? 

What about all the Layers you didn’t add arrows to (»12,VRayRawShadow12121212.RGB«, …)? 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 0
LEGEND ,
Sep 10, 2020

Copy link to clipboard

Copied

» You could use flat image files saved from your Layered EXR  documents as replacement content for populating your templates.«

True that, one could indeed create files from the Layers directly without converting them to SOs in the new source file. 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 1
Community Beginner ,
Sep 14, 2020

Copy link to clipboard

Copied

Thank you very much for waiting and for your questions. I'll try to clarify the data:
to c.pfaffenbichler:
<What is the source and what the target image?>
Left:Target file. Right:Source file. Clarified in the new attached image.
<Why are the »arrowed« Layers on the right side not numbered? >
By default the layers inside the .exr file are not numbered. I already have a script to number them automatically according to the filename. It is changed in the new "mocakup" image.

<What about all the Layers you didn’t add arrows to [...]? >
These layers are also replaced from the source file. Previously I only marked the layers that have been modified in any way (added a mask or changed the blending mode, the bitmaps are never modified. Sorry for misleading.
<» You could use flat image files saved from your Layered EXR  documents as replacement content for populating your templates.«>
Let me think it through. In this case the layers in the Target file will be already SO. Then, from the source EXR file we create temporary png files, one per layer, and the replace the SO content with the temp files created. Is that right? Also, after the replacement is done, the temporary files could be deleted. That sounds good. Is doable by scripting?

to JJMack:
<If  you installed Exr-IO to support layered exr files the plug-in will most likely have an import type dialog[...]>
Fortunately, it doesn't. Once EXR-IO in installed I can just drag'n'drop the exr file or even double-click to open it in photoshop.
<You could use flat image files saved from your Layered EXR  documents as replacement content for populating your templates. Replacement could also be saved layered PSD files.>
Sounds like you both came to the same conclusion. Using an intermediary temporary file to update the layers from the exr file to the working psd file. Am I right? If so, is there any direction you might indicate as a start point to look at? Any script that does something similiar, so I can tweak it?

Thank you very much for your help 🙂Clarification.jpg

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 14, 2020 0
Most Valuable Participant ,
Sep 14, 2020

Copy link to clipboard

Copied

I just downloaded Exr-IO and extracted the plug-in.  It look like it has a Import type interface the you may be able to bypass  by un-checking its option to always show the dialog.  So you may be able to use .exr files with Replace content.  With Photoshop script.  However my  mockup scripts con not be used unless you modify then for your personal use.  For they do not support .exr for Photoshop OpenEXR support has an inport dialog. As does Exr-IO by default. This is what I see with Replace content when I select an .exr file.  So I will mot be supporting .exr file in my mockup scripts.

image.png

 

You would need to include exr it its list of supported replacmebt file types.

rplFiles[i] = objFolders[i].getFiles(/\.(nef|cr2|crw|dcs|raf|arw|orf|dng|psd|tif|jpg|jpe|png)$/i); } 

JJMack

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 14, 2020 0
Most Valuable Participant ,
Sep 14, 2020

Copy link to clipboard

Copied

You need remember only Smart Object layer Object can have the content replaced by an other document using replace content and even if the replacement document is a layered document the smart object layer is not multiple layers its like a single pixel layer that has a recorded transform that positions sized and distorts the object for the way its used in the document.  The Distortion settings are not changed when you replace the object. Other layer type content cans be completely changed but there is no replace layer function that can be used to replace the layer with a document or a layer form an other document.

 

Mockup are normally updated be replacing the contents of one or more  smart Object layers contents.  Object are replaced with Document not a layer from an other document.  I think you need to design some process that can do what you want to achieve.   You can duplicate a layer in one document into an other document that does not replace a layer it adds an additional layer. The layer will will have the same pixel in both document.  The documents may had different canvas sizes so the layer my seem to have s different size between the two documents.  To do whatever you want to do to need to know how to use Photoshop feature to be able to design  you automated process. 

 

All your renamed layers can be exported as documents and those documents can be used the replact the contents in your Mockup document smar object layers.

JJMack

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 14, 2020 2
LEGEND ,
Sep 10, 2020

Copy link to clipboard

Copied

Are there only going to be the two images open or do they have to be identified? 

What is the naming convention identifying the two corresponding files? 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 10, 2020 0
LEGEND ,
Sep 14, 2020

Copy link to clipboard

Copied

Here is some code to help identify the Layers in two open files that have the same names except for numbers after a dot at the end of the Layer’s name. 

 

// 2020, use it at your own risk;
var theRegExp = /(.*)\.[^\.]+$/;
// do stuff;
if (app.documents.length == 2) {
var theDocs = app.documents;
var theTarget = app.activeDocument;
if (theDocs[0] == theTarget) {var theSource = theDocs[1]}
else {var theSource = theDocs[0]};
// get layers;
var theTargetLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theSource;
var theSourceLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theTarget;
// process the layers;
var theResults = new Array;
for (var m = 0; m < theTargetLayers.length; m++) {
    if (theTargetLayers[m][0].indexOf(".")!=-1) {var targetName = theTargetLayers[m][0].match(theRegExp)[1]}
    else {var targetName = theTargetLayers[m][0]};
    for (var n = 0; n < theSourceLayers.length; n++) {
        if (theSourceLayers[n][0].indexOf(".")!=-1) {var sourceName = theSourceLayers[n][0].match(theRegExp)[1]}
        else {var sourceName = theSourceLayers[n][0]};
        if (targetName == sourceName) {
            theResults.push([theTargetLayers[m], theSourceLayers[n]])
        }
    }
};
alert ("the corresponding layers are\n"+theResults.join("\n"));
};
////// collect layers //////
function collectLayersNamesIndexAndIdentifier () {
// the file;
var myDocument = app.activeDocument;
// get number of layers;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID('property'), stringIDToTypeID('numberOfLayers'));
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
var applicationDesc = executeActionGet(ref);
var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
var theLayers = new Array;
for (var m = 0; m <= theNumber; m++) {
try {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), m);
var layerDesc = executeActionGet(ref);
var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
var theKind = layerDesc.getInteger(stringIDToTypeID("layerKind"));
// if group collect values;
if (layerSet != "layerSectionEnd" && layerSet != "layerSectionStart" && isBackground != true) {
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
var theIndex = layerDesc.getInteger(stringIDToTypeID('itemIndex'));
theLayers.push([theName, theIndex, theID, theKind])
};
}
catch (e) {};
};
return theLayers
};

 

 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 14, 2020 1
Community Beginner ,
Sep 15, 2020

Copy link to clipboard

Copied

Thank you very much! This is gold to me 😄
I'll work with it. This is a great start point to put me on right track.


Thanks again!!

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 15, 2020 0
LEGEND ,
Sep 15, 2020

Copy link to clipboard

Copied

I thaught of something, though. 

It would be possible that one layer in the one file references several layers in the other if the layers’ names were identical or similar enough … 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 15, 2020 0
LEGEND ,
Sep 15, 2020

Copy link to clipboard

Copied

I have not addressed the issue of multilpe matches, but tinkered a bit with the SO-replacing.

// 2020, use it at your own risk;
var theRegExp = /(.*)\.[^\.]+$/;
// do stuff;
if (app.documents.length == 2) {
var theDocs = app.documents;
var theTarget = app.activeDocument;
if (theDocs[0] == theTarget) {var theSource = theDocs[1]}
else {var theSource = theDocs[0]};
// get layers;
var theTargetLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theSource;
var theSourceLayers = collectLayersNamesIndexAndIdentifier();
app.activeDocument = theTarget;
// process the layers;
var theResults = new Array;
for (var m = 0; m < theTargetLayers.length; m++) {
    if (theTargetLayers[m][0].indexOf(".")!=-1) {var targetName = theTargetLayers[m][0].match(theRegExp)[1]}
    else {var targetName = theTargetLayers[m][0]};
    for (var n = 0; n < theSourceLayers.length; n++) {
        if (theSourceLayers[n][0].indexOf(".")!=-1) {var sourceName = theSourceLayers[n][0].match(theRegExp)[1]}
        else {var sourceName = theSourceLayers[n][0]};
        if (targetName == sourceName) {
            theResults.push([theTargetLayers[m], theSourceLayers[n]])
        }
    }
};
alert ("the corresponding layers are\n"+theResults.join("\n"));
////////////////////////////////////
for (var o = 0; o < theResults.length; o++) {
    app.activeDocument = theSource;
    var thisOne = theResults[o];
    var theName = "~/Desktop/"+thisOne[1][0]+".psb";
// convert to so and export;
    selectLayerByID(thisOne[1][2], false);
    convertToSmartObject ();
    var theTemp = exportContents (theName);
    app.activeDocument = theTarget;
// replace contents;
    selectLayerByID(thisOne[0][2], false);
    convertToSmartObject ();
    replaceContents (theName);
// remove the temporary file;
    theTemp.remove()
    };
};
////// collect layers //////
function collectLayersNamesIndexAndIdentifier () {
// the file;
var myDocument = app.activeDocument;
// get number of layers;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID('property'), stringIDToTypeID('numberOfLayers'));
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
var applicationDesc = executeActionGet(ref);
var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
var theLayers = new Array;
for (var m = 0; m <= theNumber; m++) {
try {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), m);
var layerDesc = executeActionGet(ref);
var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
var theKind = layerDesc.getInteger(stringIDToTypeID("layerKind"));
// if group collect values;
if (layerSet != "layerSectionEnd" && layerSet != "layerSectionStart" && isBackground != true) {
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
var theIndex = layerDesc.getInteger(stringIDToTypeID('itemIndex'));
theLayers.push([theName, theIndex, theID, theKind])
};
}
catch (e) {};
};
return theLayers
};
////// smart object or not //////
function hasSmartObject(idx){
    var ref = new ActionReference(); 
    ref.putProperty( charIDToTypeID("Prpr") , stringIDToTypeID( "smartObject" )); 
    //ref.putIndex( charIDToTypeID( "Lyr " ), idx);
    ref.putIdentifier( charIDToTypeID( "Lyr " ), idx);
    var desc = executeActionGet(ref);
    if(desc.hasKey(stringIDToTypeID('smartObject'))) {return true}
    else {return false};
    };
////// based on code by mike hale and paul riggott //////
function selectLayerByID(index,add){ 
    add = undefined ? add = false:add 
    var ref = new ActionReference();
        ref.putIdentifier(charIDToTypeID("Lyr "), index);
        var desc = new ActionDescriptor();
        desc.putReference(charIDToTypeID("null"), ref );
           if(add) desc.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) ); 
          desc.putBoolean( charIDToTypeID( "MkVs" ), false ); 
       try{
        executeAction(charIDToTypeID("slct"), desc, DialogModes.NO );
    }catch(e){
    alert(e.message); 
    }
    };
////// convert to so if not one aready //////
function convertToSmartObject () {
    if (app.activeDocument.activeLayer.kind != LayerKind.SMARTOBJECT) {
    var id557 = charIDToTypeID( "slct" ); 
    var desc108 = new ActionDescriptor(); 
    var id558 = charIDToTypeID( "null" ); 
    var ref77 = new ActionReference(); 
    var id559 = charIDToTypeID( "Mn  " ); 
    var id560 = charIDToTypeID( "MnIt" ); 
    var id561 = stringIDToTypeID( "newPlacedLayer" ); 
    ref77.putEnumerated( id559, id560, id561 ); 
    desc108.putReference( id558, ref77 ); 
    executeAction( id557, desc108, DialogModes.NO );
    };
    return app.activeDocument.activeLayer
    };
////// export contents //////
function exportContents (theName) {
// =======================================================
var idplacedLayerExportContents = stringIDToTypeID( "placedLayerExportContents" );
    var desc3 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
    desc3.putPath( idnull, new File( theName ) );
executeAction( idplacedLayerExportContents, desc3, DialogModes.NO );
return File( theName )
};
////// replace contents //////
function replaceContents (theName) {
    var idplacedLayerReplaceContents = stringIDToTypeID( "placedLayerReplaceContents" );
    var desc244 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
    desc244.putPath( idnull, new File( theName ) );
    executeAction( idplacedLayerReplaceContents, desc244, DialogModes.NO );
};

 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
Reply
Loading...
Sep 15, 2020 0