This Photoshop script streamlines the process of processing and exporting individual layers (or groups of layers) from your active document. The script sets up a custom user interface where you can choose the destination folder, specify a layer name prefix, select a target resolution from predefined presets, and pick your export format (PNG or JPG) along with specific output options such as JPG quality and transparency preservation for PNGs.
#target photoshop
// Save the current ruler units
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS; // Set ruler units to pixels
// Create the main dialog
function createDialog() {
var dialog = new Window("dialog", "Layer Processor");
dialog.orientation = "column";
dialog.alignChildren = "fill";
// Destination folder group
var destGroup = dialog.add("group");
destGroup.orientation = "row";
destGroup.add("statictext", undefined, "Destination:");
var destInput = destGroup.add("edittext", undefined, "");
destInput.preferredSize.width = 300;
var browseBtn = destGroup.add("button", undefined, "Browse...");
// Prefix input group
var prefixGroup = dialog.add("group");
prefixGroup.orientation = "row";
prefixGroup.add("statictext", undefined, "Layer Prefix:");
var prefixInput = prefixGroup.add("edittext", undefined, "Layer_");
prefixInput.preferredSize.width = 150;
// Resolution presets group
var resolutionGroup = dialog.add("panel", undefined, "Target Resolution");
resolutionGroup.orientation = "row";
resolutionGroup.alignChildren = "left";
resolutionGroup.margins = 20;
var resolutionDropdown = resolutionGroup.add("dropdownlist", undefined, ["512x512", "1024x1024", "2048x2048", "4096x4096"]);
resolutionDropdown.selection = 1; // Set "1024x1024" as the default selection
// Format group
var formatGroup = dialog.add("panel", undefined, "Output Options");
formatGroup.orientation = "column";
formatGroup.alignChildren = "left";
formatGroup.margins = 20;
// File format
var formatRow = formatGroup.add("group");
formatRow.add("statictext", undefined, "Format:");
var formatDropdown = formatRow.add("dropdownlist", undefined, ["PNG", "JPG"]);
formatDropdown.selection = 0;
// JPG Quality (initially hidden)
var qualityGroup = formatGroup.add("group");
qualityGroup.visible = false;
qualityGroup.add("statictext", undefined, "JPG Quality:");
var qualitySlider = qualityGroup.add("slider", undefined, 80, 0, 100);
var qualityValue = qualityGroup.add("statictext", undefined, "80%");
// Transparency checkbox
var transparencyCheck = formatGroup.add("checkbox", undefined, "Preserve Transparency");
transparencyCheck.value = true;
// Progress bar
var progressBar = dialog.add("progressbar", undefined, 0, 100);
progressBar.visible = true;
progressBar.preferredSize.width = 350;
// Buttons group
var btnGroup = dialog.add("group");
btnGroup.orientation = "row";
btnGroup.alignment = "center";
var okBtn = btnGroup.add("button", undefined, "OK");
var cancelBtn = btnGroup.add("button", undefined, "Cancel");
// Event handlers
browseBtn.onClick = function() {
var folder = Folder.selectDialog("Select destination folder");
if (folder) {
destInput.text = folder.fsName;
}
}
formatDropdown.onChange = function() {
qualityGroup.visible = (formatDropdown.selection.text == "JPG");
transparencyCheck.enabled = (formatDropdown.selection.text == "PNG");
if (formatDropdown.selection.text == "JPG") {
transparencyCheck.value = false;
}
}
qualitySlider.onChanging = function() {
qualityValue.text = Math.round(qualitySlider.value) + "%";
}
// Store settings in dialog for access
dialog.settings = {
destFolder: destInput,
prefix: prefixInput,
resolution: resolutionDropdown,
format: formatDropdown,
quality: qualitySlider,
transparency: transparencyCheck,
progressBar: progressBar
};
// OK button handler
okBtn.onClick = function() {
if (dialog.settings.destFolder.text == "") {
alert("Please select a destination folder.");
return;
}
if (processLayers(dialog.settings)) {
alert("Processing complete!");
dialog.close();
}
}
cancelBtn.onClick = function() {
dialog.close();
}
return dialog;
}
function processLayers(settings) {
if (app.documents.length === 0) {
alert("Please open a document with layers to process.");
return false;
}
try {
var sourceDoc = app.activeDocument;
var selectedLayers = [];
try {
var idGrp = stringIDToTypeID("groupLayersEvent");
var descGrp = new ActionDescriptor();
var refGrp = new ActionReference();
refGrp.putEnumerated(charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));
descGrp.putReference(charIDToTypeID("null"), refGrp);
executeAction(idGrp, descGrp, DialogModes.NO);
var group = sourceDoc.activeLayer;
var layers = group.layers;
for (var i = 0; i < layers.length; i++) {
selectedLayers.push(layers[i]);
}
sourceDoc.activeHistoryState = sourceDoc.historyStates[sourceDoc.historyStates.length-2];
} catch (e) {
selectedLayers.push(sourceDoc.activeLayer);
}
// Show progress bar
settings.progressBar.visible = true;
// Process each layer
for (var i = 0; i < selectedLayers.length; i++) {
settings.progressBar.value = (i / selectedLayers.length) * 100;
processLayer(selectedLayers[i], sourceDoc, settings);
app.activeDocument = sourceDoc;
}
settings.progressBar.value = 100;
return true;
} catch (e) {
alert("Error: " + e);
return false;
}
}
function processLayer(layer, sourceDoc, settings) {
app.activeDocument = sourceDoc;
var bounds = layer.bounds;
var width = Math.ceil(bounds[2] - bounds[0]);
var height = Math.ceil(bounds[3] - bounds[1]);
layer.copy();
var newDoc = app.documents.add(
width,
height,
72,
settings.prefix.text + layer.name,
NewDocumentMode.RGB,
settings.transparency.value ? DocumentFill.TRANSPARENT : DocumentFill.WHITE
);
newDoc.paste();
var maxSize = Math.max(width, height);
if (width !== height) {
newDoc.resizeCanvas(maxSize, maxSize, AnchorPosition.MIDDLECENTER);
}
// Resize image to the chosen resolution
var targetResolution = settings.resolution.selection.text.split("x")[0];
newDoc.resizeImage(Number(targetResolution), Number(targetResolution), newDoc.resolution, ResampleMethod.BICUBIC);
// Save file
var file = new File(settings.destFolder.text + "/" + settings.prefix.text + layer.name);
var saveOptions;
if (settings.format.selection.text == "PNG") {
saveOptions = new PNGSaveOptions();
file = new File(file.fsName + ".png");
} else {
saveOptions = new JPEGSaveOptions();
saveOptions.quality = settings.quality.value;
file = new File(file.fsName + ".jpg");
}
newDoc.saveAs(file, saveOptions);
newDoc.close(SaveOptions.DONOTSAVECHANGES);
}
// Simplified main function
function main() {
var dialog = createDialog();
dialog.show();
}
main();
Once configured, the script works as follows:
• It first adjusts Photoshop’s ruler units to pixels for consistent measurements. • The UI dialog collects your settings including the folder for saving files, prefix for naming, target resolution (e.g., 1024×1024), and file format options. • When you click “OK”, the script processes the current document’s layers: – It attempts to gather selected layers (or, if you have grouped multiple layers, it processes each layer within the group). – For each layer, the script copies the layer, creates a new document sized to the layer’s bounds, and pastes the layer. – It automatically adjusts the new document’s canvas to a square shape if needed and resizes the image to your chosen resolution. – The output file is then saved in either PNG or JPG format based on your settings; JPG also allows you to adjust the quality. • A progress bar provides real-time feedback on the process. • On successful processing of all layers, an alert confirms that the operation is complete. • Finally, it restores the original Photoshop preferences and reassigns the active document.
Tutorial Guidelines:
- Prerequisites:
- Open Adobe Photoshop.
- Ensure you have a document open that contains the layers you want to process.
- Familiarize yourself with Photoshop scripting (access via File > Scripts).
- Running the Script:
- Execute the script through Photoshop’s script menu or your preferred scripting environment.
- The script automatically sets the ruler units to pixels for uniform measurements.
- Configuring the User Interface:
- Destination Folder: Use the “Browse…” button to select the folder where processed images will be saved.
- Layer Prefix: Enter a desired prefix that will be added to the exported file names.
- Target Resolution: Select one of the preset resolutions (e.g., 1024×1024) to define the size of the exported images.
- Output Options: • Choose the file format from the dropdown (PNG or JPG). • If you select JPG, a quality slider appears to adjust the compression percentage. • The “Preserve Transparency” checkbox is enabled for PNGs to maintain layer transparency.
- Processing Layers:
- Click “OK” after configuring your settings.
- The script will attempt to detect and process the active layer or a group of layers.
- A progress bar updates as each layer is processed.
- For each layer, the script: • Determines the layer’s bounds. • Creates a new document using those dimensions. • Centers and resizes the layer content based on the chosen target resolution. • Saves the new document in the selected format with the specified layer prefix.
- Upon completion, a confirmation alert appears indicating the processing is complete.
- Canceling the Process:
- If you change your mind or wish to adjust your settings before processing, you can click “Cancel” to exit the dialog without any changes.