Copy link to clipboard
Copied
Hey Everyone! I've recently entered the world of Scripting on Photoshop by helping myself of AI to write Code.
Lately i've been trying to create a Script that allows me to Input long lists of HEX Codes and display them as Swatches on a Group (allowing me to name this group). However, as many times I change the code, according to Chat GPTs suggestions, It seems it always encounters an error (such as the screenshots attached).
This is the Code in question
#target photoshop
function main() {
if (app.documents.length === 0) {
alert("Please open a document before running this script.");
return;
}
// Prompt the user for the swatch name prefix
var swatchNamePrefix = prompt("Enter the prefix for the swatch names:", "Swatch");
if (!swatchNamePrefix) return;
// Prompt the user for hex color codes
var hexCodes = prompt("Enter hex color codes separated by commas:", "#FF5733,#33FF57,#3357FF");
if (!hexCodes) return;
// Split the hex codes into an array and remove any extra whitespace
var hexArray = hexCodes.split(",");
for (var i = 0; i < hexArray.length; i++) {
hexArray[i] = hexArray[i].trim();
}
// Function to convert HEX to RGB
function hexToRgb(hex) {
var bigint = parseInt(hex.replace("#", ""), 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return { red: r, green: g, blue: b };
}
// Function to create a new swatch
function addSwatch(name, color) {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putClass(stringIDToTypeID("colorSwatch"));
desc.putReference(charIDToTypeID("null"), ref);
var swatchDesc = new ActionDescriptor();
swatchDesc.putString(charIDToTypeID("Nm "), name);
swatchDesc.putObject(charIDToTypeID("Clr "), stringIDToTypeID("RGBC"), color);
desc.putObject(charIDToTypeID("Usng"), stringIDToTypeID("colorSwatch"), swatchDesc);
executeAction(charIDToTypeID("Mk "), desc, DialogModes.NO);
}
// Add each hex code as a new swatch
for (var i = 0; i < hexArray.length; i++) {
var hex = hexArray[i];
if (/^#([0-9A-F]{3}){1,2}$/i.test(hex)) {
var rgb = hexToRgb(hex);
var color = new ActionDescriptor();
color.putDouble(charIDToTypeID("Rd "), rgb.red);
color.putDouble(charIDToTypeID("Grn "), rgb.green);
color.putDouble(charIDToTypeID("Bl "), rgb.blue);
try {
addSwatch(swatchNamePrefix + " " + (i + 1), color);
} catch (e) {
alert("Failed to create swatch for hex code: " + hex);
}
} else {
alert("Invalid hex code: " + hex);
}
}
alert("Swatches created successfully with prefix: " + swatchNamePrefix);
}
main();
Copy link to clipboard
Copied
However, as many times I change the code, according to Chat GPTs suggestions, It seems it always encounters an error
By @Alejandro266549369287
Welcome to the early days of crowd based open-source AI generated coding. :]
IMHO, It would be better if the AI code came from Adobe – built directly into Photoshop as an IDE with debugging and other features.