Sub topic 15
Going further: calling actions from ExtendScript
Actions and the Batch command cover most repetitive work. Sometimes you need logic they cannot express: choosing a folder at run time, skipping files by name, collecting errors, or writing output in a layout Batch cannot produce. ExtendScript is Photoshop's scripting language, and it can play the actions you already recorded. This chapter shows how to combine the two.
This chapter assumes you can record, edit and run actions and use Batch with its source and destination settings. It also assumes you know basic JavaScript syntax: variables, loops, functions and if statements. ExtendScript is based on an older JavaScript dialect (ES3), so it has no let, const, arrow functions or template strings.
Where scripting fits
An action is good at replaying Photoshop commands. A script is good at deciding what to do and which files to do it to. The most useful pattern keeps each tool in its role. The action holds the image edits you recorded in the Actions panel. The script handles files, folders, conditions and error reporting.
| Need | Best tool |
|---|---|
| Replay a fixed sequence of edits | Action |
| Run an action on a folder with simple naming rules | Batch or a droplet |
| Resize and convert only | Image Processor |
| Custom folder logic, skipping files, error log, unusual output paths | ExtendScript calling an action |
Playing one action with app.doAction
The doAction method of the app object plays an action by name. It takes two arguments: the action name and the name of the set that contains it.
#target photoshop
// Run one existing action on the active document.
// The first argument is the action name, the second is the action set name.
app.doAction("Resize for Web", "My Actions");The first line, #target photoshop, tells the script host to run the file in Photoshop. Without it, double-clicking the file may open it in an editor instead of running it.
Keep these rules in mind:
- The action set must be loaded in the Actions panel. If it is not,
doActioncannot find the action. Load a saved.atnfile first. - Names must match exactly, including spaces and capitalization. A mismatch throws a runtime error.
- The action runs on the active document. Open or activate the document before the call.
- The call is synchronous. The next line of the script does not run until the action finishes.
Running the script
There are three common ways to run a script.
- Choose File > Scripts > Browse and pick the
.jsxfile. - Save the file in Photoshop's
Presets/Scriptsfolder and restart Photoshop. The script then appears in the File > Scripts menu. - Run it from a script editor connected to Photoshop, such as the ExtendScript debugger extension for Visual Studio Code. This route is best while developing because you can set breakpoints and see error messages.
A folder-level script without actions
Before combining the two, look at what a pure script does. This example opens each image in a chosen folder, shrinks any image wider than 1600 pixels while keeping its proportions, saves a JPEG copy into a web subfolder and closes the original without saving changes.
#target photoshop
app.displayDialogs = DialogModes.NO;
var inputFolder = Folder.selectDialog("Choose the folder of images to process");
if (inputFolder) {
var outputFolder = new Folder(inputFolder.fsName + "/web");
if (!outputFolder.exists) {
outputFolder.create();
}
var files = inputFolder.getFiles(function (f) {
return f instanceof File && /\.(jpe?g|png|tiff?)$/i.test(f.name);
});
var maxWidth = 1600;
for (var i = 0; i < files.length; i++) {
var doc = app.open(files[i]);
var w = doc.width.as("px");
var h = doc.height.as("px");
if (w > maxWidth) {
var newHeight = Math.round(h * maxWidth / w);
doc.resizeImage(UnitValue(maxWidth, "px"), UnitValue(newHeight, "px"), doc.resolution, ResampleMethod.BICUBICSHARPER);
}
var baseName = doc.name.replace(/\.[^\.]+$/, "");
var jpegOptions = new JPEGSaveOptions();
jpegOptions.quality = 10;
doc.saveAs(new File(outputFolder.fsName + "/" + baseName + ".jpg"), jpegOptions, true, Extension.LOWERCASE);
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}Several details here matter later:
app.displayDialogs = DialogModes.NOstops Photoshop from showing option dialogs, such as JPEG options or file-open prompts, that would otherwise block the loop.- The filter function passed to
getFileskeeps only files, not subfolders, whose names end in a supported extension. Theiflag makes the match case-insensitive, soPHOTO.JPGis included. doc.width.as("px")converts the document width to a plain number of pixels, whatever the ruler units are.- In
saveAs, the third argumenttruesaves a copy. The original file is not renamed or replaced. - JPEG quality runs from 0 to 12 in scripts. A value of 10 is a high-quality setting.
Combining a script and an action
Now replace the hard-coded resize with your recorded action. The script opens each file, plays the action, saves the result and records any file that fails.
#target photoshop
var ACTION_NAME = "Resize for Web";
var SET_NAME = "My Actions";
var previousDialogs = app.displayDialogs;
app.displayDialogs = DialogModes.NO;
var inputFolder = Folder.selectDialog("Choose the folder of images to process");
var failures = [];
var processed = 0;
if (inputFolder) {
var outputFolder = new Folder(inputFolder.fsName + "/processed");
if (!outputFolder.exists) {
outputFolder.create();
}
var files = inputFolder.getFiles(function (f) {
return f instanceof File && /\.(jpe?g|png|tiff?)$/i.test(f.name);
});
for (var i = 0; i < files.length; i++) {
var doc = null;
try {
doc = app.open(files[i]);
app.doAction(ACTION_NAME, SET_NAME);
var baseName = doc.name.replace(/\.[^\.]+$/, "");
var jpegOptions = new JPEGSaveOptions();
jpegOptions.quality = 10;
doc.saveAs(new File(outputFolder.fsName + "/" + baseName + ".jpg"), jpegOptions, true, Extension.LOWERCASE);
processed++;
} catch (e) {
failures.push(files[i].name + ": " + e.message);
}
if (doc) {
try {
doc.close(SaveOptions.DONOTSAVECHANGES);
} catch (closeError) {
// The action may already have closed the document.
}
}
}
app.displayDialogs = previousDialogs;
alert("Processed " + processed + " file(s). Failures: " + failures.length +
(failures.length ? "\n\n" + failures.join("\n") : ""));
} else {
app.displayDialogs = previousDialogs;
}The script saves the dialog mode before changing it and restores it afterwards. Otherwise Photoshop would keep suppressing dialogs for your later manual work in the same session.
The try and catch blocks are the main gain over Batch. When one file fails, the loop moves on, and you get a list at the end instead of a stalled run.
Common problems
The action is not found. The error message mentions the action or the set. Check that the set is loaded in the Actions panel and that both names match character for character. A set that holds a duplicate action name plays the first match.
The script hangs on a dialog. DialogModes.NO suppresses most option dialogs. An action step that contains an Insert Stop or a modal control (the dialog toggle in the action's first column) may still pause the run. Remove those from actions meant for unattended use, or make a copy of the action without them. Test with two or three files before running a full folder.
The action expects a layer or selection that is missing. The same portability rules from earlier chapters apply. An action that selects "Layer 1" by name fails on a flat JPEG. The script reports this as an error for that file, which makes such problems easier to find than in Batch.
The active document changed. If the action opens or closes documents, your doc variable may point to a closed document. When that is possible, read app.activeDocument after the action instead of reusing the old variable.
Old files get overwritten. Saving into the input folder with the same name and extension replaces the original. Write to a separate output folder, as both scripts above do.
When to stay with Batch
A script costs more to write and maintain than a Batch run. Choose it when you need at least one of these:
- Filtering by something Batch cannot see, such as file size, name patterns or image dimensions.
- A custom summary or log of failures.
- Output folders or names built from data, such as one subfolder per shoot date.
- One script that runs several actions in sequence with logic between them.
If you only need to run one action on one folder with a standard naming scheme, Batch or a droplet is faster to set up and easier for colleagues to use.
Exercise
A script calls app.doAction("Sharpen Web", "Web Set") inside a loop over 200 files. The first file fails with an error saying the action cannot be found, although the action exists in your saved Web Set.atn file. What is the most likely cause, and what two other things should you check?
Show answer
The most likely cause is that the action set is not loaded in the Actions panel, so doAction cannot see it. Load the .atn file first. Then check that the action name and set name match exactly, including spaces and capitalization, and that the set name is the name shown in the panel, which may differ from the .atn file name.
Exercise
In the combined script, why is the doc.close call wrapped in its own try and catch block, and why does the script save with the "save as a copy" argument set to true?
Show answer
An action can close the document itself, so a later doc.close call may throw an error, and the inner try and catch keeps that from ending the loop. Saving as a copy leaves the original file untouched and avoids renaming the open document, so the source image is never overwritten.