Search code examples
javascriptphotoshop-script

Convert all existing clipping masks to smart object in Photoshop Using Javascript


Is it possible to convert all existing clipping masks to smart objects in Photoshop using Javascript?

enter image description here

I mean converting the image and its shape clipping mask to single smart object.


Solution

  • It's possible: Although this script just looks for a clipping mask and the layer it's ascribed to. No groups as I don't know what your PSD is like. But you get the idea.

    The real answers were here and here and here

    // select the source image
    var srcDoc = app.activeDocument;
    var numOfLayers = srcDoc.layers.length;
    
    var smart = false;
    for (var i = 0; i< numOfLayers-1; i++)
    {
      //select that layer as you go along
      srcDoc.activeLayer = srcDoc.artLayers[i];
    
      if (is_clipping_layer(srcDoc.layers[i]) == true)
      {
        // alert(thisLayer.name + "\n    " + srcDoc.layers[i+1].name);
        select_layer(srcDoc.layers[i+1].name, true)
        smart = true;
        break;
      }
    }
    
    if(smart == true)
    {
      convert_to_smart_object();
    }
    
    
    
    function is_clipping_layer()
    {
      var l = activeDocument.activeLayer;
      return (l.grouped == true && l.kind == LayerKind.NORMAL)
    }
    
    function convert_to_smart_object()
    {
      var idnewPlacedLayer = stringIDToTypeID( 'newPlacedLayer' );
      executeAction(idnewPlacedLayer, undefined, DialogModes.NO);
    }
    
    
    function select_layer(nm, add)
    {   
      try
      {
    
        var r = new ActionReference();
        r.putName(stringIDToTypeID("layer"), nm);
        var d = new ActionDescriptor();
        d.putReference(stringIDToTypeID("null"), r);
        if (add == true) d.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
        executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
      }
    
      catch (eeek)
      {
        alert(eeek);
      }
    }