Photoshop Source Code


So I know the formatting sucks. I need to look into it, but I simply don't have the time at the moment. Bear with me, and sorry!

Welcome to my Photoshop Scripting Page.
This has become a place to showcase some of the scripting work I've discovered and written over the last year or two.

Since blogger doesn't allow me to do traditional "post style" on anything but the main blog page, I'll have to do some color formatting to keep things from getting too jumbled.
Dates will be in "gray"
Comments and such will be in "green"
and code blocks will be in "blue".

This page's posts will work in descending chronology.
Happy reading!

Once the files are localized (see previous entry), and if the script is written to be modular (Such as my timestamp script) they can be plugged into other scripts. Previously, I'd been using the '//@include' method, but I've found for localizing, they need to be evaluated...such as below. Set up this way, the functions can then be called from other scripts!

 #target Photoshop
//evaluate the timeStamp Script Function

var timeStamp = getTimestamp();//get the timeStamp

This way, we can make a reference to the timeStamp, calling the function from another script. This alleviates us from re-writing this function over and over into our scripts!

Found out how to localize the default Photoshop Plug-ins folder today. This allows me to distribute folders full of script goodies to other users and everything will work regardless of which version they are using as long as they install the package in their Plug-Ins folder.

#target Photoshop

var pluginsFolder = Folder(app.path+"/"+localize("$$$/Plug-Ins=Plug-Ins"));
files = pluginsFolder.getFiles();

alert (decodeURI(files));


A coworker needed a way to find the bottom most layerSet of an activeLayer. Over lunch, I whipped this up:

#target photoshop
 //get the root LayerSet of the activeLayer

var doc = app.activeDocument; //ref to document
activeLayer_Tree = [doc.activeLayer]; //setup an array with the activeLayer as it's initial member
var rootLayerSet; //temp result variable to be defined later

for (var a = 0;a<activeLayer_Tree.length;a++){ //loop through the array recursively
    if (activeLayer_Tree[a].parent&&activeLayer_Tree[a].parent.typename == "LayerSet"){ //if it has a parent, and if it's a LayerSet, then...
        //alert (true+"\nparent: "+activeLayer_Tree[a].parent+"\ngrandParent: "+activeLayer_Tree[a].parent.parent+"\nparentType: "+activeLayer_Tree[a].parent.typename+"\nchild: "+activeLayer_Tree[a].child)
        activeLayer_Tree.push(activeLayer_Tree[a].parent); //push it into the array
        a = activeLayer_Tree.length; //if we don't meet the conditions, kill the loop
    rootLayerSet = activeLayer_Tree[activeLayer_Tree.length-1]; //define the result

alert (; //tell the user what we've got.

ever wondered how to proportionally reduce a document so that the long side always equals 600 px? I did! so here it is:

#target photoshop

//if an image's longest side is longer than 600 px, then reduce it proportionally so that the longest side = the defined amount.

var reduceTo = 600;
var doc = app.activeDocument;

if (doc.width>reduceTo||doc.height>reduceTo){
      if (doc.width>doc.height){
            alert ("the new doc size will be "+reduceTo+" x "+Math.round(((doc.height*reduceTo)/doc.width))); doc.resizeImage(reduceTo,Math.round(((doc.height*reduceTo)/doc.width)))
                  alert ("the new doc size will be "+Math.round(((doc.width*reduceTo)/doc.height))+" x "+reduceTo); doc.resizeImage(Math.round(((doc.width*reduceTo)/doc.height)),reduceTo)  
      }//if width or height
}else{alert ("File is >= reduction Amount")}//if larger than reduction


Sometimes I need to find a specific layerSet in Photoshop.
Unfortunately, you can't just tell Photoshop to find a layer set by it's name, because if  (let's call it) "LayerSetA" is nested inside of another layerSet(s), Photoshop will tell you that there is no such element, and you'll error out.

For example, lets say "glass set" is nested three sets deep:

For 'Shop to find this, you'd need to tell it exactly how to locate it: doc.layerSets[0].layerSets[0].layerSets[0].layerSets.getByName("LayerSetA");

...which is unreasonable.

For this to work, you'd need to know EXACTLY where that group is EVERY TIME you went to look for it. To make matters worse, this would get much muddier if  if there are other sets sharing parents.

The best way I've found (there's probably a better/faster way) is to loop through the entire document, finding each object of type "[Layer Set]" and populating an array with them, then, you can iterate through the array and check for that name. Once you find the sets you need, you can run your code.

/////////////////CODE BLOCK////////////////
#target photoshop
//can be included in other scripts

//consider adding this block to your scripts
if (documents.length){
    alert ("please open a document and run this script again")
}//if docs

sets = [];
sets = findSets();

function findSets(){
    ////////////////GLOBAL: VARIABLE AND ARRAY DECLARATIONS/////////////////
    var doc = app.activeDocument;
    array = [];
    array = findAllSets(doc, array);
    ////////////////////GLOBAL: LOGIC//////////////////////////////////
    if (array.length){
        //alert ("findallSets returned: "+array);
    }//if array.length

    ////////////////////////GLOBAL: FUNCTIONS//////////////////////////////////
    function findAllSets(doc, arrayOut){
        //////////////////////LOCAL: VARS and ARRAYS//////////////////////////////
        setNames = [];
        setsGrp = [doc.layers, arrayOut];
        //////////////////////LOCAL: LOGIC//////////////////////////////
        for (var count = 0; count&lt;setsGrp.length;count++){
            arrayOut =  recursiveSetPopulation(setsGrp[count], arrayOut);
        }//for count
        for (var z = 0; z&lt;arrayOut.length;z++){
            setNames[z] = arrayOut[z].toString().replace("[LayerSet ", "");
            setNames[z] = setNames[z].toString().replace("]", "");
        }//for z
        if (setNames.length !=0){
            //alert ("setNames = "+setNames);
            //alert ("arrayOut = "+arrayOut);
            alert ("this file doesn't appear to have any layerSets");
        //////////////////////LOCAL: FUNCTIONS//////////////////////////////
        function recursiveSetPopulation(arrayIn, outputArray){
                if (arrayIn.toString() == "[Layers]"){
                    for (var i=0;i&lt;arrayIn.length;i++){
                        if (arrayIn[i].typename == "LayerSet"){  
                    }//for i
                    for (var i=0;i&lt;arrayIn.length;i++){
                        for (var a=0;a&lt;arrayIn[i].layers.length;a++){
                            if (arrayIn[i].layers[a].typename == "LayerSet"){
                        }//for a
                    }//for i
            return outputArray;
        return arrayOut;



Sometimes, you just know the name of the files you're looking for, not necessarily where they are...or are too lazy to look.

#target photoshop
//2011, developed in CS2, use at your own risk.

//////////////This script does the following:
//////////////Using a top folder specified by the user,
//////////////locates all nested folders and populates them into an array
//////////////using that array, finds all files and populates them into an array(if they match the conditions in "var fileTypes")
//////////////iterates through the files
//////////////checks if their file size is above a specific condition, and will downsize them if it meets the criteria,
//////////////else, it will move on.

if (app.documents.length){
    alert ("Please close any open documents and run this script again.");

function main(){
    //////////////VARIABLES and ARRAY DECLARATIONS////////////////////
    stringArray = ["Please Copy Paste a filePath here"];
    flexArray = [];
    var stageVar = 0;
    flexArray = getInfo(stageVar, stringArray, flexArray, 0);
    var myFolder = Folder(flexArray[1]);//put a path to your top folder here (in this format- "C:\\Documents\\etc)
    var fileTypes = (/\.(jpg|tga|tif|psd|)$/i);//add file types here if you need more (follow the convention!)
    var maxDimension = UnitValue(500, 'px');//define the maximum pixel dimension before downsizing
    app.preferences.rulerUnits = Units.PIXELS;  //we'll use pixel dimensions
    files =[];
    folders = [];
    completeList = [folders, files];


    for(var index = 0;index&amp;lt;completeList[0].length;index++){
        completeList = findNested(folders, completeList, index);
    alert ("folders: "+completeList[0]+"\nfiles: "+completeList[1]);//commented out for now, uncomment if you want to see what's being found
    for (var a=0;a&amp;lt;completeList[1].length;a++){
        var doc = app.activeDocument;
        if (doc.width&amp;lt;maxDimension||doc.height&amp;lt;maxDimension){
            if (doc.width&amp;gt;doc.height){
                var B = doc.width;
                if (doc.height&amp;gt;doc.width){
                    var B = doc.height;
                    if (doc.width&amp;gt;doc.height){
                        var B = doc.height;
            if (B&amp;gt;maxDimension){
                alert ("we need to down size");
                //downSize here
        var JPEGSOptions = new JPEGSaveOptions();
        JPEGSOptions.embedColorProfile = false;
        JPEGSOptions.formatOptions = FormatOptions.STANDARDBASELINE;
        JPEGSOptions.matte = MatteType.NONE;
        JPEGSOptions.quality = 12;
        //save here   

    function findNested(folderIn, arrayIn, index){
        tempItem = [];
        tempItem = folderIn[index].getFiles();
        for (var a=0;a&amp;lt;tempItem.length;a++){
            if (typeof tempItem[a].open == "undefined"){
        return arrayIn;
    //var stageVar = 0;

function getInfo(stageVar, stringArray, arrayOut, stringArIndex){
    tempArray = [];
    tempArray = arrayOut.shift();//remove the first item(stageVar)
    for (var i=1;i&amp;lt;2;i++){//loop as much as options
    var input = prompt(stringArray[stringArIndex], input);//ask the user for input   
        if (input == "undefined"){//if the user attempts no input...
            alert ("you must enter a valid project name");//yell at them
            stageVar = 0;//do not pass go
            i = 0;//do not collect 200 dollars.
            if (input == null){//if the user cancels..
                alert ("operation cancelled");//tell them what they've done
                stageVar = 0;//do not allow progress
                i = 3;//but kill the loop (shut down the prompt)
                arrayOut.push(stageVar);//push the stageVariable in as zero
                return arrayOut;//return the result
            }else{//if the user gives something useful...
                stageVar = stageVar +1;//advance the stage variable to allow progress
                arrayOut.unshift(stageVar);//push the newly updated stageVar onto the front of the array
                arrayOut.push(input);//push the userInput into the end of the array
                var i = 3;//kill the loop
                return arrayOut;//return the array to the user for later use


No comments:

Post a Comment