Skip to content Skip to sidebar Skip to footer

Photoshop Javascript To Get All Layers In The Active Document

I'm sure it should be discussed before by Photoshop scripters. I write a solution as following. I think it's logically right, but the result is not correct. Anybody can help to che

Solution 1:

I know this is an old thread, but this might be useful for someone.

I was looking for a function that would get me all the ArtLayers in a Photoshop comp, including layers nested in groups. The above function was returning undefined, so I modified it and got it to work.

var doc = app.activeDocument;
var allLayers = [];
var allLayers = collectAllLayers(doc, allLayers);

functioncollectAllLayers (doc, allLayers){
    for (var m = 0; m < doc.layers.length; m++){
        var theLayer = doc.layers[m];
        if (theLayer.typename === "ArtLayer"){
            allLayers.push(theLayer);
        }else{
            collectAllLayers(theLayer, allLayers);
        }
    }
    return allLayers;
}

Solution 2:

To get all the layers (and sub layers) you have to have a recursive function

var allLayers = newArray();
var theLayers = collectAllLayers(app.activeDocument, 0);


functioncollectAllLayers (theParent, level)
{
  for (var m = theParent.layers.length - 1; m >= 0; m--)
  {
    var theLayer = theParent.layers[m];
    if (theLayer.typename != "ArtLayer")
    {
      allLayers.push(level + theLayer.name);
      collectAllLayers(theLayer, level + 1)
    }
  }
}

Solution 3:

Minor expansion on Ghoul Fool's post to only get all VISIBLE art layers in the active document. :P

// Get layers in a documentvar sourceDocument = app.activeDocument;
var visibleLayers  = [];
var visibleLayers  = collectAllLayers(sourceDocument, visibleLayers);

// Print out total layers found
alert(visibleLayers.length);


// Recursively get all visible art layers in a given documentfunctioncollectAllLayers (parent, allLayers)
{
    for (var m = 0; m < parent.layers.length; m++)
    {
        var currentLayer = parent.layers[m];
        if (currentLayer.typename === "ArtLayer")
        {
            if(currentLayer.visible)
            {
                allLayers.push(currentLayer);
            }
        }
        else
        {
            collectAllLayers(currentLayer, allLayers);
        }
    }
    return allLayers;
}

Solution 4:

function selectAllLayers() {
    var desc29 = new ActionDescriptor();
    var ref23 = new ActionReference();
    ref23.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
    desc29.putReference(charIDToTypeID('null'), ref23);
    executeAction(stringIDToTypeID('selectAllLayers'), desc29, DialogModes.NO);
}

Post a Comment for "Photoshop Javascript To Get All Layers In The Active Document"