Scripting Rename layer with Artboard Size Prefix
Looking for a way to rename a selected layer using the artboard size that the layer is within.
When using Generator, I'm hoping to be able to add that as a folder name to the start of the file name.
I allmost have this script working, but it grabs the first layer size, not the selected size.
var layer = app.activeDocument.layers[0];
Will grab the first layer, not selected layer
var layer = app.activeDocument.activeLayer;
Gives error:
Error 21: undefined is not an object.
Line: 12
-> var width = (ab[2] - ab[0]);
Based on this from @Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/automatically-change-artboard-name-to-artboard-dimensions-in-pixels/m-p/13300750#M681172
// Retrieve the first layer of the active document
var layer = app.activeDocument.layers[0];
//var layer = app.activeDocument.activeLayer;
//alert(layer)
// Calculate the bounds of the artboard containing the selected layer
var ab = artboard_rectangle(layer);
// Calculate half of the artboard width and height
var width = (ab[2] - ab[0]);
var height = (ab[3] - ab[1]);
// Construct a new name for the layer using half of the artboard's width and height
var newName = width + "x" + height;
// Rename the selected layer with the new name
layer.name = newName;
// Check if there is an active document
if (app.activeDocument) {
// Get the currently selected layer
var selectedLayer = app.activeDocument.activeLayer;
if (selectedLayer) {
// Prefix to be added
var prefix = width + "x" + height + '/';
// Check if the layer name is not empty
if (selectedLayer.name !== "") {
// Add the prefix to the layer name
selectedLayer.name = prefix + selectedLayer.name;
} else {
alert("Selected layer has no name.");
}
} else {
alert("No layer is selected.");
}
} else {
alert("No active document found.");
}
// Function to calculate the bounds of an artboard
function artboard_rectangle(layer) {
try {
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("artboard"));
if (layer) r.putIdentifier(stringIDToTypeID("layer"), layer.id);
else r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
var d = executeActionGet(r).getObjectValue(stringIDToTypeID("artboard")).getObjectValue(stringIDToTypeID("artboardRect"));
var bounds = new Array();
bounds[0] = d.getUnitDoubleValue(stringIDToTypeID("top"));
bounds[1] = d.getUnitDoubleValue(stringIDToTypeID("left"));
bounds[2] = d.getUnitDoubleValue(stringIDToTypeID("right"));
bounds[3] = d.getUnitDoubleValue(stringIDToTypeID("bottom"));
return bounds;
} catch(e) {
alert(e);
}
}
