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

How to get the swatch name in extendscript using fillColor?

Explorer ,
Jul 23, 2024 Jul 23, 2024

Hi,

Now I using this way to get the swatch name using fillColor.

// Function to get the name of the swatch based on the fill color
function getSwatchNameByFillColor(fillColor) {
    var doc = app.activeDocument;
    var swatches = doc.swatches;
    
    for (var i = 0; i < swatches.length; i++) {
        var swatch = swatches[i];
        if (compareColors(fillColor, swatch.color)) {
            return swatch.name;
        }
    }
    
    return "No matching swatch found";
}

// Function to compare two colors
function compareColors(color1, color2) {
    if (color1.typename == color2.typename) {
        switch (color1.typename) {
            case "SpotColor":
                return color1.spot.name == color2.spot.name;
            case "GradientColor":
                return color1.gradient.name == color2.gradient.name;
            case "PatternColor":
                return color1.pattern.name == color2.pattern.name;
            case "RGBColor":
                return color1.red == color2.red && color1.green == color2.green && color1.blue == color2.blue;
            case "CMYKColor":
                return color1.cyan == color2.cyan && color1.magenta == color2.magenta && color1.yellow == color2.yellow && color1.black == color2.black;
            case "GrayColor":
                return color1.gray == color2.gray;
            case "LabColor":
                return color1.l == color2.l && color1.a == color2.a && color1.b == color2.b;
            default:
                return false;
        }
    }
    return false;
}

// Check if there is a selection
if (app.selection.length > 0) {
    // Get the selected object
    var selectedObject = app.selection[0];

    // Get the fill color of the selected object
    var fillColor = selectedObject.fillColor;

    // Get the swatch name based on the fill color
    var swatchName = getSwatchNameByFillColor(fillColor);

    // Output the swatch name
    alert("Swatch Name: " + swatchName);
} else {
    alert("No object is selected.");
}

 

Any alternative or easiest way is there?. Please help.

TOPICS
How-to , Scripting
126
Translate
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
no replies

Have something to add?

Join the conversation
Adobe