• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

I am trying to make a script to use in Illustrator for extraction Colors from Gradient & Saving ...

New Here ,
Jun 04, 2023 Jun 04, 2023

Copy link to clipboard

Copied

I am trying to make a script to use in Illustrator for extraction Colors from Gradient and Saving them to ColorGroup. Got stuck on Line: 51 "var newSwatch = colorGroup.addSwatch(color);" , can someone help? 
Saying in advance.. I have many alerts which are not needed in script, but I used them in previous steps to debug when ran into issues before and just haven't cleaned it up for now. 

 

#target illustrator

// Get the active document
var doc = app.activeDocument;

// Prompt user to select a gradient from the document
var gradientName = promptForGradient(doc);

alert("Selected gradientName: " + gradientName); // Display gradientName value

if (gradientName !== null) {
    // Prompt user to enter the number of steps per percentage
    var stepsPerPercentage = promptForStepsPerPercentage();
    alert("Steps per percentage: " + stepsPerPercentage); // Display stepsPerPercentage value

    if (stepsPerPercentage !== null) {
        // Prompt user to enter the color group name
        var colorGroupName = promptForColorGroupName();
        alert("Color group name: " + colorGroupName); // Display colorGroupName value

        if (colorGroupName !== null) {
            // Check if the color group already exists
            var colorGroup = getColorGroupByName(colorGroupName);

            // If the color group doesn't exist, create it
            if (colorGroup === null) {
                colorGroup = doc.swatchGroups.add();
                colorGroup.name = colorGroupName;
            }

            // Get the specified gradient from the document
            var gradient = getGradientByName(gradientName);
            if (gradient) {
                // Extract colors from the gradient at each step
                for (var i = 0; i <= 100; i++) {
                    var rampPoint = i / (100 * stepsPerPercentage);
                    var existingStop = findStopByRampPoint(gradient, rampPoint);

                    // Check if a gradient stop with the same ramp point already exists
                    if (existingStop !== null) {
                        // If a stop already exists, use its color instead of adding a new stop
                        var color = existingStop.color;
                    } else {
                        // If no stop exists, add a new gradient stop and get the color
                        var gradientStop = gradient.gradientStops.add();
                        gradientStop.rampPoint = rampPoint;
                        var color = gradientStop.color;
                    }

                    // Add the color to the color group
                    var newSwatch = colorGroup.addSwatch(color);
                    var r = Math.round(color.red);
                    var g = Math.round(color.green);
                    var b = Math.round(color.blue);
                    newSwatch.name = "R=" + r + " G=" + g + " B=" + b;
                }
            }

            // Save the document with the extracted colors
            var savePath = "~/Desktop/extracted_colors.ai";
            doc.saveAs(new File(savePath));

            // Close the document
            // doc.close(SaveOptions.DONOTSAVECHANGES);
        } else {
            alert("Invalid color group name. Script execution terminated.");
        }
    } else {
        alert("Invalid steps per percentage value. Script execution terminated.");
    }
} else {
    alert("No gradient selected. Script execution terminated.");
}

// Function to prompt user for selecting a gradient
function promptForGradient(doc) {
    var gradientNames = [];
    var numGradients = doc.gradients.length;

    // Populate an array with gradient names
    for (var i = 0; i < numGradients; i++) {
        gradientNames.push(doc.gradients[i].name);
    }

    // Create a dialog box with dropdown menu for gradient selection
    var dialog = new Window("dialog", "Select Gradient");
    var dropdown = dialog.add("dropdownlist", undefined, gradientNames);
    dropdown.selection = 0;

    // Store the selected gradient name
    var selectedGradientName = null;

    // OK button event listener
    dropdown.onChange = function () {
        selectedGradientName = gradientNames[dropdown.selection.index];
    };

    // Add buttons to the dialog box
    var buttonsGroup = dialog.add("group");
    buttonsGroup.alignment = "right";
    buttonsGroup.add("button", undefined, "OK");
    buttonsGroup.add("button", undefined, "Cancel");

    // OK button event listener
    buttonsGroup.children[0].onClick = function () {
        dialog.close(selectedGradientName);
    };

    // Cancel button event listener
    buttonsGroup.children[1].onClick = function () {
        dialog.close(null);
    };

    // Show the dialog box
    dialog.show();

    // Print the selected gradient name
    if (selectedGradientName) {
        alert("Selected gradientName: " + selectedGradientName);
    }

    return selectedGradientName;
}

// Function to prompt user for entering steps per percentage
function promptForStepsPerPercentage() {
    var dialog = new Window("dialog", "Enter Steps Per Percentage");
    dialog.add("statictext", undefined, "Steps per percentage:");
    var inputBox = dialog.add("edittext", undefined, "1");
    inputBox.characters = 5;

    // Store the entered value
    var enteredValue = null;

    // Add buttons to the dialog box
    var buttonsGroup = dialog.add("group");
    buttonsGroup.alignment = "right";
    buttonsGroup.add("button", undefined, "OK");
    buttonsGroup.add("button", undefined, "Cancel");

    // OK button event listener
    buttonsGroup.children[0].onClick = function () {
        var value = parseFloat(inputBox.text);
        if (!isNaN(value) && value > 0) {
            enteredValue = value;
            dialog.close(enteredValue);
        } else {
            alert("Invalid steps per percentage value. Please enter a positive number.");
        }
    };

    // Cancel button event listener
    buttonsGroup.children[1].onClick = function () {
        dialog.close(null);
    };

    // Show the dialog box
    dialog.show();

    // Print the entered value
    if (enteredValue) {
        alert("Entered steps per percentage: " + enteredValue);
    }

    return enteredValue;
}

// Function to prompt user for entering the color group name
function promptForColorGroupName() {
    var dialog = new Window("dialog", "Enter Color Group Name");
    dialog.add("statictext", undefined, "Color group name:");
    var inputBox = dialog.add("edittext", undefined, "Extracted Colors");
    inputBox.characters = 20;

    // Store the entered value
    var enteredValue = null;

    // Add buttons to the dialog box
    var buttonsGroup = dialog.add("group");
    buttonsGroup.alignment = "right";
    buttonsGroup.add("button", undefined, "OK");
    buttonsGroup.add("button", undefined, "Cancel");

    // OK button event listener
    buttonsGroup.children[0].onClick = function () {
        enteredValue = inputBox.text;
        dialog.close(enteredValue);
    };

    // Cancel button event listener
    buttonsGroup.children[1].onClick = function () {
        dialog.close(null);
    };

    // Show the dialog box
    dialog.show();

    // Print the entered value
    if (enteredValue) {
        alert("Entered color group name: " + enteredValue);
    }

    return enteredValue;
}

// Function to retrieve gradient by name
function getGradientByName(name) {
    var numGradients = doc.gradients.length;

    // Iterate through the gradients and find the one with the matching name
    for (var i = 0; i < numGradients; i++) {
        var gradient = doc.gradients[i];
        if (gradient.name === name) {
            return gradient;
        }
    }

    return null;
}

// Function to retrieve color group by name
function getColorGroupByName(name) {
    var numColorGroups = doc.swatchGroups.length;

    // Iterate through the color groups and find the one with the matching name
    for (var i = 0; i < numColorGroups; i++) {
        var colorGroup = doc.swatchGroups[i];
        if (colorGroup.name === name) {
            return colorGroup;
        }
    }

    return null;
}

// Function to find a gradient stop by ramp point
function findStopByRampPoint(gradient, rampPoint) {
    var numStops = gradient.gradientStops.length;

    // Iterate through the gradient stops and find the one with the matching ramp point
    for (var i = 0; i < numStops; i++) {
        var stop = gradient.gradientStops[i];
        if (stop.rampPoint === rampPoint) {
            return stop;
        }
    }

    return null;
}
TOPICS
Experiment , How-to , Scripting , Type

Views

213

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
Guide ,
Jun 04, 2023 Jun 04, 2023

Copy link to clipboard

Copied

colorGroup.addSwatch() takes a swatch as an argument, not a color, hence the error. 

Votes

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 Expert ,
Jun 04, 2023 Jun 04, 2023

Copy link to clipboard

Copied

to expand of what femkeblanco said, you would need to add a swatch to the documents first, then you can add that swatch to the swatch group

 

// Add the color to the color group
var newSwatch = doc.swatches.add();
colorGroup.addSwatch(newSwatch);
//newSwatch.color = color;

Votes

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 Expert ,
Jun 04, 2023 Jun 04, 2023

Copy link to clipboard

Copied

LATEST

Hi @Dimitri A.L. ,

Try the following action script. The follwoing action will add colors from the selection to the new color group. 

var actionStr = [
    "/version 3",
    "/name [ 5",
    "	5365742031",
    "]",
    "/isOpen 1",
    "/actionCount 1",
    "/action-1 {",
    "	/name [ 9",
    "		416464436f6c6f7273",
    "	]",
    "	/keyIndex 0",
    "	/colorIndex 0",
    "	/isOpen 0",
    "	/eventCount 1",
    "	/event-1 {",
    "		/useRulersIn1stQuadrant 0",
    "		/internalName (ai_plugin_swatches)",
    "		/localizedName [ 8",
    "			5377617463686573",
    "		]",
    "		/isOpen 1",
    "		/isOn 1",
    "		/hasDialog 1",
    "		/showDialog 0",
    "		/parameterCount 1",
    "		/parameter-1 {",
    "			/key 1835363957",
    "			/showInPalette 4294967295",
    "			/type (enumerated)",
    "			/name [ 15",
    "				4e657720436f6c6f722047726f7570",
    "			]",
    "			/value 17",
    "		}",
    "	}",
    "}",
    ""
].join("\n");

var actionFileDestStr = Folder.desktop + "/MyAction.aia";
var actionFile = File(actionFileDestStr);
actionFile.open('w');
actionFile.write(actionStr);
actionFile.close();
app.loadAction(actionFile);
app.doScript("AddColors", "Set 1");
actionFile.remove();
app.unloadAction("Set 1", '');
Best regards

Votes

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