Snippets

Kyle Martinez Get Average Gradient

Created by Kyle Martinez
(function() {
    function convertRGBtoHEX(color) {
        var r = color.red;
        var g = color.green;
        var b = color.blue;
        return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }

    try {
        var selectedObj = app.selection[0];
        var gradientColor = selectedObj.fillColor.gradient;
        
        var gradientStops = gradientColor.gradientStops;
        var numGradientStops = gradientStops.length;

        var averageRed = 0;
        var averageGreen = 0;
        var averageBlue = 0;

        for (var s = 0; s < numGradientStops; s++) {
            var stop = gradientStops[s];
            var stopColor = stop.color;

            averageRed += stopColor.red;
            averageGreen += stopColor.green;
            averageBlue += stopColor.blue;
        }

        var averageColor = {
            "red": averageRed / numGradientStops,
            "green": averageGreen / numGradientStops,
            "blue": averageBlue / numGradientStops
        };

        var hexColor = convertRGBtoHEX(averageColor).toUpperCase();
        alert(hexColor);
    } catch (err) {
        alert(err);
    }
})();

Comments (0)