Search code examples
javascriptmacosphotoshopphotoshop-script

Photoshop: Loop until desired value is reached


I run the below script to check Luminosity of the pixel based on Color Sampler picked. And then automaticaly adjust exposure until Luminosity of the desired pixel has reached 235~.

//Get color sampler values
var colorSampler = app.activeDocument.colorSamplers[0];

//RGB values
var Red = colorSampler.color.rgb.red
var Green = colorSampler.color.rgb.green
var Blue = colorSampler.color.rgb.blue
var RGB = [ Red, Green, Blue ];

//Get Luminosity
var averageLuminosity = [(Red + Green + Blue)/3 ];
    

LumaCheck();

function LumaCheck () {
    if (averageLuminosity < 215) {
        Luma20();
    } else if (averageLuminosity < 225) {
        Luma10();
    } else if (averageLuminosity < 230) {
        Luma5();
    } else if (averageLuminosity < 233) {
        Luma1();
    } else if (averageLuminosity < 235) {
        Luma1();
        Luma1();
    } else (averageLuminosity >= 235) {
    //do nothing    
    }
}

It works great on whites, although struggles on color pixels: where RGB values of the pixel are very different. As soon as it reaches 235, of any of the Red/Green or Blue channels - it stops.

How would you go on creating a loop, until all RGB values reach "greater or equal to 235 value"?

I tried doing a simple loop, but it won't stop at all. If anyone could point me to the right direction, it would be much appreciated!

while (averageLuminosity < 235) {
    Luma1();
    if (averageLuminosity >= 235)
        break;
}


Solution

  • In terms of the actual loop, Something like this could work but has a lot of overhead:

    var avrLum = 0
    
    for(var i = 0; i <= 235; i++) {
      for(var j = 0; j <= 235; j++) {
        for(var k = 0; k <= 235; k++) {
          avrLum = (i+j+k)/3
          LumaCheck(avrLum);
        } 
      }
    }
    
    function LumaCheck (averageLuminosity) {
        if (averageLuminosity < 215) {
            Luma20();
        } else if (averageLuminosity < 225) {
            Luma10();
        } else if (averageLuminosity < 230) {
            Luma5();
        } else if (averageLuminosity < 235) {
            Luma1();
        }
    }
    

    For loops are generally avoided due to slowness but are really the only operations I can think of in JS that can handle looping using ranges without using arrays and other forms of manipulations. This will at least go through all the values Red, Blue and Green can be.

    Let me know if this at least helps.

    (BTW this solution is only in regards to the loop)