Script optimization - merge adjustment layers

Discussion of Photoshop Scripting, Photoshop Actions and Photoshop Automation in General

Moderators: xbytor, DavideBarranca, Paul MR

Post Reply
undavide

Script optimization - merge adjustment layers

Post by undavide » Thu Mar 06, 2014 10:54 pm

Hi,
I've put together a (working) script for a friend of mine: basically he has tons of files with bitmap layers and clipped adjustment layers, like:



and wants to merge all the adjustment layers so that the final result is:



Mind you, if you select, say, layer D and its two clipped adjustments and merge, the resulting bitmap layer is going to be named "Hue/Saturation 1" - which is bad, I need the layer to be called "D" like the original.

What I've come up is as follows:

Code: Select allfunction mergeDown() {
   var idMrgtwo = charIDToTypeID( "Mrg2" );
   var desc1110 = new ActionDescriptor();
   executeAction( idMrgtwo, desc1110, DialogModes.NO );
}

function flatClip() {
   var d = app.activeDocument;
   for (var i = app.activeDocument.layers.length - 1; i >= 0; i--) {
      // Last Layer in the Stack
      if (i == 0) {
         if (d.layers[0].kind != LayerKind.NORMAL) {
            d.activeLayer = d.layers;
            mergeDown();
         }
         return true;
      } else {
         // other Layers
         if (app.activeDocument.layers[i-1].kind != LayerKind.NORMAL) {
            d.activeLayer = d.layers[i-1];
            mergeDown();
            return false;
         } else {
            continue;
         }
      }
   }
}

var isDone = flatClip();
while (!isDone) {
   isDone = flatClip();
}

It works, friend is happy, took me not too much time to write. But to my eyes it looks ugly!
The logic is simple - traverse the layer stack bottom up, if a bitmap layer has an adjustment layer above, select it and merge down.
The application seems to me messy: a flatClip function with nested ifs, returning a boolean checked against in a while loop - I'm sure there's a better, more compact and elegant (possibly faster?) way to perform the same task.

Since there's no better way to learn than from others' experience, I'll be happy if someone would share his/her best take on this problem.
Thank you!

Davide Barranca
http://www.davidebarranca.com

Post Reply