Search code examples
photoshopextendscriptphotoshop-script

Get layer ID from Photoshop layer


Not sure if I'm doing this right. I'm trying to locate a layer. I can normally do that by group name & layer name. However that does present problems if there are duplicate names. So instead I'll try and find their unique layer ID.

I think this is correct:

var srcDoc = app.activeDocument;
var numOfLayers = srcDoc.layers.length;

// main loop
for (var i = numOfLayers -1; i >= 0  ; i--)
{
   var ref = new ActionReference();
   ref.putIndex( charIDToTypeID( "Lyr " ), i);
   var layerDesc = executeActionGet(ref);
   var layerID = layerDesc.getInteger(stringIDToTypeID('layerID'));
   var currentLayer = srcDoc.layers[i].name;
   alert(layerID + " " + currentLayer);
}

... Only I expected the ID to be a larger random string, not a int. Firstly, have I got this right? And secondly is there a way to get the layer ID from the activeLayer?


Solution

  • IDs are interegers in PS and they are unique for a document only: they always start at 1 and then new layers and layer operations change ID counter by +1 so it's normal to have IDs in hundreds after a while.

    To get an id of the active layer, change the reference to target:

    var ref = new ActionReference();
    ref.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt')); // reference is active layer
    var layerDesc = executeActionGet(ref);
    var layerID = layerDesc.getInteger(stringIDToTypeID('layerID'));
    alert(layerID);
    

    P.S. this will work only with one active layer. For multiple layers you'll have you use a function I posted here: Get selected layers

    P.P.S. note that your original code won't work with groups: indices of DOM and indices of AM aren't the same. You need to traverse layers in AM list to get proper indices.