Script that replaces one color with another with tolerance. - RealWorld forums

Log-in or register.

Script that replaces one color with another with tolerance.

Foxxey
on August 13th 2023

I'm trying to create a script that replaces oldColor with newColor with a tolerance (0-100) in percent. Sadly I couldn't find a way to get HSV from a particular variable so I am stuck on using RGB (wait... does it use BGR format instead??) and scraping the values from the 3x8 bits. This is my code:

Configuration.AddColorButton("oldColor", "Old Color", "Select the color to be replaced", 0x0000FF);
Configuration.AddColorButton("newColor", "New Color", "Select the new color", 0xFF0000);
Configuration.AddSlider("tolerance", "Tolerance", "How different can the color be from Old Color?", 0, 100, 8);
var oldColor = Configuration.GetValue("oldColor");
var newColor = Configuration.GetValue("newColor");
var tolerance = Configuration.GetValue("tolerance");
var image = Document.RasterImage;
var sizeX = image.sizeX;
var sizeY = image.sizeY;
function colorsAreSimilar(var color1, var color2, var tolerance)
{
    var diffRed = Math.abs((color1 >> 16) & 0xFF - (color2 >> 16) & 0xFF);
    var diffGreen = Math.abs((color1 >> 8) & 0xFF - (color2 >> 8) & 0xFF);
    var diffBlue = Math.abs(color1 & 0xFF - color2 & 0xFF);
    // or switch diffRed and diffBlue if its BGR

    return (diffRed <= tolerance * 2.55) && (diffGreen <= tolerance * 2.55) && (diffBlue <= tolerance * 2.55);
}
for (var x = 0; x < sizeX; x++) {
    for (var y = 0; y < sizeY; y++) {
        var pixelColor = image.GetPixelColor(x, y, 0, 0);

        if (colorsAreSimilar(pixelColor, oldColor, tolerance)) {
            image.SetPixelColor(x, y, 0, 0, newColor);
        }
    }
}

And I am getting this error: Expected identifier

Anonymous
on July 29th

hi

Page views: 398       Posts: 2      
I wish there were...
Vista & Win 7 icons
What about ICL files?