How can I create a curves adjustment layer in JavaScript?

Explorer ,
Oct 12, 2014 Oct 12, 2014

Copy link to clipboard

Copied

I've been trying a few different approaches along the lines of:

var newLayer = activeDocument.artLayers.add(); // Create a new ArtLayer object

newLayer.name = "MyLayer"; // name it for later reference

app.activeDocument.artLayers.getByName("MyLayer").kind=LayerKind.CURVES

When I do, I get an error that I can only change the layer's kind to text or normal.  Anyone know how to create a new curves adjustment layer via script?

TOPICS
Actions and scripting

Views

4.3K

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Community Professional ,
Oct 12, 2014 Oct 12, 2014

Copy link to clipboard

Copied

Have you tried to see if ScriptingListener.plugin records code for this?

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Oct 13, 2014 Oct 13, 2014

Copy link to clipboard

Copied

SciptListener does work, but isn't clean.  Is there not a way to code it?  Part of what I'm trying to do is just get a handle on curves using JavaScript in Photoshop.  Even with ScriptListener, I seem unable to adjust the curve once I create it.

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Community Professional ,
Oct 13, 2014 Oct 13, 2014

Copy link to clipboard

Copied

SciptListener does work, but isn't clean. 

That statement does not make a lot of sense.

A common practice to get more readable code is to pack the AM code into functions.

I seem unable to adjust the curve once I create it.

Do you mean change the settings or raise the dialog?

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Oct 13, 2014 Oct 13, 2014

Copy link to clipboard

Copied

Agree, functions are an option.  Maybe I just need to get used to that.

For the curves adjustments, I'm trying to set multiple points on a curve.  Having trouble both with ScriptListener and writing JavaScript.

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Community Professional ,
Oct 13, 2014 Oct 13, 2014

Copy link to clipboard

Copied

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Oct 13, 2014 Oct 13, 2014

Copy link to clipboard

Copied

Not sure I'm tracking here... I'm looking to adjust the overall luminosity, not individual RGB curves.

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Community Professional ,
Oct 13, 2014 Oct 13, 2014

Copy link to clipboard

Copied

So change the code to affect the composite channel or use the same values for all three channels.

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Oct 14, 2014 Oct 14, 2014

Copy link to clipboard

Copied

I have a script I think will do what you want. You set 2 color picker spots (first one is the "good" color, second is the "bad" color). The script creates a curves adjustment layer and alters the curves to match the colors at those 2 spots...it will adjust to make the color at spot 2 the same as the color at spot 1. You also can set the average area to sample from. It's a fairly big script but I can post it if you want.

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Oct 14, 2014 Oct 14, 2014

Copy link to clipboard

Copied

Here is the script I use. The way it works is you choose 2 spots with the color picker tool. Spot 1 is the "good" color and spot 2 is the "bad" color. The script will attempt to use a curves adjustment layer to match the area at spot to with the area at spot one. The variable Avg will give you a radius around each point to average the colors at the spots chosen.

Start with the raster (or smart object) layer selected that contains the colors to compare. Choose your 2 spots. Run the script. This will create a curves adjustment layer above your start layer named similar to your start layer with a number after it. It will also invert the mask on the curves layer. You then unmask the area you wish to "fix" by painting with white on the mask at that area. It's best to use a low flow and/or low opacity and a soft brush in order to blend in around the edges of where you unmask.

What it does is first compares all the channels (red, green, and blue) for each spot and determines the best curves adjustment with the composite channel (all 3 channels combined...this is the main curves you see when you first create a curves adjustment layer). It will then recheck and fine tune any hue/saturation differences by slightly adjusting each channel individually. Let me know if you have any questions.

#target Photoshop

var startRulerUnits = app.preferences.rulerUnits;

var startTypeUnits = app.preferences.typeUnits ;

var startDisplayDialogs = app.displayDialogs;

app.preferences.rulerUnits = Units.PIXELS;

app.preferences.typeUnits = TypeUnits.PIXELS;

app.displayDialogs = DialogModes.NO;

doc=app.activeDocument;

var colorRefin=new SolidColor;

var colorRefout=new SolidColor;

R=new Array;

G=new Array;

B=new Array;

var dialogMode=DialogModes.NO;

Avg=20;

size=[0+" px",0+" px",doc.width,doc.height];

function arrayComp(array1,array2) {

    if (array1.length != array2.length) return false;

    i=array1.length-1;

    while {

        if (array1 != array2) return false;

        i--;

    }

    return true;

}

// Name the layer with the next higher number available for the given name.

function nameLayer(fromLayer) {

    var rlayer=new String(fromLayer.name);

    l=rlayer.length-1;

    while (l>0) {

        if (isNaN(rlayer) || rlayer==" ") break;

        l--;

    }

    l++;

    baseLayer=new String(rlayer.substring(0,l));

    nl=parseInt(rlayer.substring(l,rlayer.length)) +1;

    if (isNaN(nl)) {

        l++;

        baseLayer=baseLayer+" ";

        nl=1;

    }

    while (isLayer(baseLayer+nl)) nl++;

    return baseLayer+nl;

}

// Check to see if a layer by "name" exists.

function isLayer(name) {

    i=doc.layers.length-1;

    while ((i+1)>0) {

        if (doc.layers.name == name) return true;

        i--;

    }

    return false;

}

//Get the layer number of a layer

function getLayerNum(reflay) {

    i=0;

    while (doc.layers) {

        if (doc.layers == reflay) return i;

        else i++;

    }

}

// Find the appropriate Rasterized layer in the stack.

function getRasterLayer(num) {

    i=num;

    while (doc.layers) {

        if ((doc.layers.kind == LayerKind.NORMAL || doc.layers.kind == LayerKind.SMARTOBJECT) && arrayComp(doc.layers.bounds,size)) return doc.layers;

        else i++;

        if (i>doc.layers.length-1) return doc.layers[doc.layers.length-1];

    }

    return -1;

}

// Set up the new curves layer in the stack and rename it.

function setColorLayer(st,colLayer) {

    i=st;

    l=1;

    refLay=null;

    while (doc.layers) {

        if (doc.layers.name.substring(0,13)=="Color Adj") {

            refLay=doc.layers;

            l++;

        }

        i--;

        if (i<0) break;

    }

    if (refLay) {

        colLayer.name="Color Adj " + l;

        colLayer.move(refLay,ElementPlacement.PLACEBEFORE);

    }

    else colLayer.name="Color Adj 1";

}

function hasSelection(doc) {

    if(doc == undefined) doc = activeDocument;

    var res = false;

    var as = doc.activeHistoryState;

    doc.selection.deselect();

    if (as != doc.activeHistoryState) {

        res = true;

        doc.activeHistoryState = as;

    }

    return res;

}

// Average the colors if needed

function getSelectionColor(s,A){

        if (!s) { s=1;}

        if (!A) {A=1;}

        CP=doc.colorSamplers;

        s=s-1;

        sampleSize=A;

        r=((A-1)/2);

        x=Math.round(CP.position[0]-r);

        y=Math.round(CP.position[1]-r);

        doc.selection.select([[x, y], [x+sampleSize, y], [x+sampleSize, y+sampleSize], [x, y+sampleSize]], SelectionType.REPLACE, 0, false);

        if (doc.activeLayer.kind!=LayerKind.NORMAL) {

            doc.selection.copy();

            templay=doc.paste(true);

            doc.selection.select([[x, y], [x+sampleSize, y], [x+sampleSize, y+sampleSize], [x, y+sampleSize]], SelectionType.REPLACE, 0, false);

            templay.applyAverage();

            var sColor = new SolidColor();

            sColor=CP.color;

            templay.remove();

        }

        else {

            doc.activeLayer.applyAverage();

            var sColor = new SolidColor();

            sColor=CP.color;

            executeAction( charIDToTypeID('undo'), undefined, DialogModes.NO );

        }

        doc.selection.deselect();

        return sColor;

}

// Read from the .ini file if present

function readini() {

    var SCRIPTS_FOLDER = new Folder(app.path + '/' + localize("$$$/ScriptingSupport/InstalledScripts=Presets/Scripts"));

    ini=new File([SCRIPTS_FOLDER + "/TMAColorAdjust.ini"]);

    if (ini.created) {

        $.evalFile(ini);

        return true;

    };

    ini.close();

};

// Make Curves Adjustment Layer

function addCurve() {

    var desc1 = new ActionDescriptor();

    var ref1 = new ActionReference();

    ref1.putClass(PSClass.AdjustmentLayer);

    desc1.putReference(PSString.Null, ref1);

    var desc2 = new ActionDescriptor();

    var desc3 = new ActionDescriptor();

    desc3.putEnumerated(PSString.presetKind, PSString.presetKindType, PSString.presetKindDefault);

    desc2.putObject(PSKey.Type, PSClass.Curves, desc3);

    desc1.putObject(PSKey.Using, PSClass.AdjustmentLayer, desc2);

    executeAction(PSEvent.Make, desc1, DialogModes.NO);

};

// Set Curves Adjustment Layer

function setCurve(IN,OUT,chan) {

    switch (chan) {

        case 0:

        case null:

        curveChan=PSEnum.Composite;

        break;

        case 1:

        curveChan=PSEnum.Red;

        break;

        case 2:

        curveChan=PSEnum.Green;

        break;

        case 3:

        curveChan=PSEnum.Blue;

        break;

    }

    var desc1 = new ActionDescriptor();

    var ref1 = new ActionReference();

    ref1.putEnumerated(PSClass.AdjustmentLayer, PSType.Ordinal, PSEnum.Target);

    desc1.putReference(PSString.Null, ref1);

    var desc2 = new ActionDescriptor();

    var list1 = new ActionList();

    var desc3 = new ActionDescriptor();

    var ref2 = new ActionReference();

    ref2.putEnumerated(PSClass.Channel, PSClass.Channel, curveChan);

    desc3.putReference(PSClass.Channel, ref2);

    var list2 = new ActionList();

    var desc4 = new ActionDescriptor();

    desc4.putDouble(PSKey.Horizontal, 0);

    desc4.putDouble(PSKey.Vertical, 0);

    list2.putObject(PSClass.Point, desc4);

    var desc5 = new ActionDescriptor();

    desc5.putDouble(PSKey.Horizontal, IN);

    desc5.putDouble(PSKey.Vertical, OUT);

    list2.putObject(PSClass.Point, desc5);

    var desc6 = new ActionDescriptor();

    desc6.putDouble(PSKey.Horizontal, 255);

    desc6.putDouble(PSKey.Vertical, 255);

    list2.putObject(PSClass.Point, desc6);

    desc3.putList(PSKey.Curve, list2);

    list1.putObject(PSClass.CurvesAdjustment, desc3);

    desc2.putList(PSKey.Adjustment, list1);

    desc1.putObject(PSKey.To, PSClass.Curves, desc2);

    executeAction(PSEvent.Set, desc1, dialogMode);

}

function setSwatch() {

    var desc1 = new ActionDescriptor();

    var ref1 = new ActionReference();

    ref1.putProperty(PSClass.Color, PSKey.Colors);

    desc1.putReference(PSString.Null, ref1);

    executeAction(PSEvent.Reset, desc1, DialogModes.NO);

//    executeAction(PSEvent.Exchange, desc1, DialogModes.NO);

};

function pickBrush() {

    var desc1 = new ActionDescriptor();

    var ref1 = new ActionReference();

    ref1.putClass(PSClass.PaintbrushTool);

    desc1.putReference(PSString.Null, ref1);

    executeAction(PSEvent.Select, desc1, DialogModes.NO);

};

function clipPoint(cpin,cpout) {

    if (cpin==cpout) return [128,128];

    if (cpin>cpout) {

        if (cpin > 128) return [cpout,Math.max(Math.min((cpout*3-cpin*2),255),0)];

        else return [cpout,Math.max(Math.min((cpout*2-cpin),255),0)];

    }

    if (cpout>cpin) {

        if (cpin<128) return [cpout,Math.max(Math.min((cpin*3-cpout*2),255),0)];

        else return [cpout,Math.max(Math.min((cpin*2-cpout2),255),0)];

    }

}

function loadVars() {

    PSClass = function() {};

    PSEnum = function() {};

    PSEvent = function() {};

    PSForm = function() {};

    PSKey = function() {};

    PSType = function() {};

    PSUnit = function() {};

    PSString = function() {};

  PSClass.AdjustmentLayer = cTID('AdjL');

  PSClass.Channel = cTID('Chnl');

  PSClass.Color = cTID('Clr ');

  PSClass.Curves = cTID('Crvs');

  PSClass.CurvesAdjustment = cTID('CrvA');

  PSClass.PaintbrushTool = cTID('PbTl');

  PSClass.Point = cTID('Pnt ');

  PSEnum.Blue = cTID('Bl  ');

  PSEnum.Composite = cTID('Cmps');

  PSEnum.Green = cTID('Grn ');

  PSEnum.Red = cTID('Rd  ');

  PSEnum.Target = cTID('Trgt');

  PSEvent.Invert = cTID('Invr');

  PSEvent.Exchange = cTID('Exch');

  PSEvent.Make = cTID('Mk  ');

  PSEvent.Reset = cTID('Rset');

  PSEvent.Select = cTID('slct');

  PSEvent.Set = cTID('setd');

  PSKey.Adjustment = cTID('Adjs');

  PSKey.Colors = cTID('Clrs');

  PSKey.Curve = cTID('Crv ');

  PSKey.Horizontal = cTID('Hrzn');

  PSKey.To = cTID('T   ');

  PSKey.Type = cTID('Type');

  PSKey.Using = cTID('Usng');

  PSKey.Vertical = cTID('Vrtc');

  PSString.Null = sTID('null');

  PSString.presetKind = sTID('presetKind');

  PSString.presetKindCustom = sTID('presetKindCustom');

  PSString.presetKindDefault = sTID('presetKindDefault');

  PSString.presetKindType = sTID('presetKindType');

  PSType.Ordinal = cTID('Ordn');

};

cTID = function(s) { return app.charIDToTypeID(s); };

sTID = function(s) { return app.stringIDToTypeID(s); };

if (doc.colorSamplers.length ==2) {

    if (hasSelection(doc)) {

        sel=doc.selection.bounds;

        Sel=new Array([sel[0],sel[1]],[sel[2],sel[1]],[sel[2],sel[3]],[sel[0],sel[3]]);

        Area=parseInt(((sel[3]-sel[1]+sel[2]-sel[0])/2));

        doc.selection.deselect();

    }

    else sel=false;

   

    actLayer=doc.activeLayer;

//    if (actLayer.isBackgroundLayer ) alert("Background Layer");

    if (doc.layers.length < 2) actLayer=actLayer.duplicate();

    startLayer=getRasterLayer(getLayerNum(doc.activeLayer));

    doc.activeLayer=startLayer;

   

    // Check to see if a selection was made. If so, we want to average

    //  the color for that size area but centered on the Color Picker spot.

    // Or, alternately, set Avg (above) to a specific value you wish to use in case of no selection.

    // If not, just use the color from the Color Picker itself.   

    if (sel) {

        colorRefin=getSelectionColor(2,Area);

        colorRefout=getSelectionColor(1,Area);

    }

    else if (Avg>1) {

        Area=Avg;

        colorRefin=getSelectionColor(2,Area);

        colorRefout=getSelectionColor(1,Area);

    }

    else {

        colorRefin=doc.colorSamplers[1].color; //Color Sampler #2=Bad Color

        colorRefout=doc.colorSamplers[0].color; //Color Sampler #1=Good Color

    }

    // Reselect original selection in case we want to re-run this with the same average area.

   

    Rin=Math.round(colorRefin.rgb.red);

    Gin=Math.round(colorRefin.rgb.green);

    Bin=Math.round(colorRefin.rgb.blue);

    Rout=Math.round(colorRefout.rgb.red);

    Gout=Math.round(colorRefout.rgb.green);

    Bout=Math.round(colorRefout.rgb.blue);

    loadVars();

    curveLayer=addCurve();

    if ((Rin+Gin+Bin)>(Rout+Gout+Bout)) {

        if (Rin>Gin) {

            if (Gin>Bin) {

                compIn=Bin;

                compOut=Bout;

            }

            else {

                compIn=Gin;

                compOut=Gout;

            }

        }

        else {

            if (Rin>Bin) {

                compIn=Bin;

                compOut=Bout;

            }

            else {

                compIn=Rin;

                compOut=Rout;

            }

        }

    }

    else {

        if (Rin<Gin) {

            if (Gin<Bin) {

                compIn=Bin;

                compOut=Bout;

            }

            else {

                compIn=Gin;

                compOut=Gout;

            }

        }

        else {

            if (Rin<Bin) {

                compIn=Bin;

                compOut=Bout;

            }

            else {

                compIn=Rin;

                compOut=Rout;

            }

        }

    }

    setCurve(compIn,compOut,0);

    newLayer=doc.activeLayer;

    newLayer.name=nameLayer(actLayer);

    newLayer.move(actLayer,ElementPlacement.PLACEBEFORE);

    doc.activeLayer=startLayer;

    colorRefin=doc.colorSamplers[1].color;

    doc.activeLayer=newLayer;

    Rin=Math.round(colorRefin.rgb.red);

    Gin=Math.round(colorRefin.rgb.green);

    Bin=Math.round(colorRefin.rgb.blue);

    setCurve(Rin,Rout,1);

    setCurve(Gin,Gout,2);

    setCurve(Bin,Bout,3);

    doc.activeLayer=startLayer;

    colorRefin=doc.colorSamplers[1].color;

    doc.activeLayer=newLayer;

    Rdif=Math.round(colorRefin.rgb.red)-Rin;

    Gdif=Math.round(colorRefin.rgb.green)-Gin;

    Bdif=Math.round(colorRefin.rgb.blue)-Bin;

    Rw=Rout-Rin;

    Gw=Gout-Gin;

    Bw=Bout-Bin;

    Rin=Math.round(colorRefin.rgb.red);

    Gin=Math.round(colorRefin.rgb.green);

    Bin=Math.round(colorRefin.rgb.blue);

    if (Rdif!=0) {

        Rin=(Rout-(Rw*Rw/Rdif));

        setCurve(Rin?Rin:Rout,Rout,1);

    }

    if (Gdif!=0) {

        Gin=(Gout-(Gw*Gw/Gdif));

        setCurve(Gin?Gin:Gout,Gout,2);

    }

    if (Bdif!=0) {

        Bin=(Bout-(Bw*Bw/Bdif));

        setCurve(Bin?Bin:Bout,Bout,3);

    }

    newLayer.move(actLayer,ElementPlacement.PLACEBEFORE);

    setSwatch();

    pickBrush();

    executeAction(PSEvent.Invert, undefined, DialogModes.NO);

//    if (sel) doc.selection.select(Sel);

};

else alert("You must choose 2 spots using the color picker tool");

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Mar 02, 2017 Mar 02, 2017

Copy link to clipboard

Copied

I tried this and it errors out on the while { take on line 24.

I think there supposed to be () ....( but I can't figure out what goes in the parentheses).

Does this run on your machine?

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Mar 23, 2021 Mar 23, 2021

Copy link to clipboard

Copied

@jugenjury 

Wow! This script seems to be just what I've been looking for!

 

I faced a problem trying to use it, however.

Would you please help me figure it out?

 

The script as it is right now has an :information: emoji on line 21. If I change nothing and just copy-paste the script, I get an error. If I put (i>0) instead like so:

....

i=array1.length-1;

while (i>o) {

 if (array1 != array2) return false;

....

then Photoshop freezes upon exe executing the script. 

 

Could you please help me find the reason it fails? Is it in line 21?

 

Thank you!

 

P.S I have a simple .PSD file with two rasterized layers and two color pickers on similar colors. I start the script with the layer I want to apply adjustment.

Likes

translate

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines