Sub topic 14
Automating open and save with ExtendScript
This chapter assumes you know the menu workflow for PSD, JPEG, and PNG from earlier chapters. You should also be comfortable with basic JavaScript: variables, functions, if, and for loops. ExtendScript is Adobe's older JavaScript dialect (roughly ES3), so it has no let, const, arrow functions, or JSON by default.
Where ExtendScript fits
ExtendScript lets a script do what you do in the File menu: create documents, open files, and save them in other formats. It works best for repeatable saves. Examples are exporting every file in a folder as JPEG, or writing a PSD master and a PNG copy of the same design.
Save files with a .jsx extension, then run them from File > Scripts > Browse. You can also keep them in the Photoshop Presets/Scripts folder so they appear in the File > Scripts menu after a restart.
The scripting model has three parts:
appis the Photoshop application object.Documentobjects represent open files.app.documentslists them all, andapp.activeDocumentis the one in front.- Save option objects, such as
PhotoshopSaveOptions,JPEGSaveOptions, andPNGSaveOptions, hold the settings you would normally pick in a dialog.
Creating a document
app.documents.add() takes width, height, resolution, name, color mode, and initial fill, in that order.
// ExtendScript (run via File > Scripts > Browse)
var doc = app.documents.add(
new UnitValue(1920, "px"),
new UnitValue(1080, "px"),
72,
"Banner",
NewDocumentMode.RGB,
DocumentFill.WHITE
);This creates a 1920 by 1080 pixel RGB document at 72 ppi. DocumentFill.WHITE produces a locked Background layer filled with white. If you want transparency, which matters for PNG later, use DocumentFill.TRANSPARENT. That fill creates an ordinary layer with no pixels instead of a Background layer.
Wrapping values in UnitValue makes the unit explicit. A bare number is read in the current ruler units from Preferences, so it can mean different things on different machines.
Opening a file
// ExtendScript
var file = File.openDialog("Choose an image");
if (file) {
var doc = app.open(file);
alert(doc.name + ": " + doc.width + " x " + doc.height);
}File.openDialog() returns null when the user cancels, so the if (file) check is required. Without it, app.open(null) throws an error.
doc.width and doc.height are UnitValue objects. They print with their unit and follow the ruler unit setting. To get a plain pixel number, use doc.width.as("px").
Saving: the `saveAs` call
All three saves use one method:
doc.saveAs(saveIn, options, asCopy, extensionType)| Argument | Meaning |
|---|---|
| `saveIn` | A `File` object for the target path. |
| `options` | A save options object that selects the format and its settings. |
| `asCopy` | `true` writes a copy and leaves the open document tied to its original name and format. This matches **Save a Copy**. |
| `extensionType` | `Extension.LOWERCASE`, `Extension.UPPERCASE`, or `Extension.NONE`. |
The options object, not the file extension, decides the format. If you pass JPEGSaveOptions with a path ending in .png, you get a JPEG with a misleading name. Keep the extension and the options object in agreement.
Saving a layered PSD
// ExtendScript: save the active document as a layered PSD
var doc = app.activeDocument;
var psdOpts = new PhotoshopSaveOptions();
psdOpts.layers = true;
psdOpts.embedColorProfile = true;
psdOpts.maximizeCompatibility = true;
doc.saveAs(new File("~/Desktop/banner.psd"), psdOpts, true, Extension.LOWERCASE);layers = true keeps layers, masks, and smart objects editable. maximizeCompatibility stores a flattened preview inside the file so other programs can read it. The cost is a larger file. The ~ in the path stands for your home folder.
Saving JPEG and PNG copies
// ExtendScript: save a JPEG copy and a PNG copy of the active document
var doc = app.activeDocument;
var jpegOpts = new JPEGSaveOptions();
jpegOpts.quality = 10; // scale is 0 to 12
jpegOpts.embedColorProfile = true;
jpegOpts.formatOptions = FormatOptions.STANDARDBASELINE;
doc.saveAs(new File("~/Desktop/banner.jpg"), jpegOpts, true, Extension.LOWERCASE);
var pngOpts = new PNGSaveOptions();
pngOpts.interlaced = false;
doc.saveAs(new File("~/Desktop/banner.png"), pngOpts, true, Extension.LOWERCASE);Both calls use asCopy = true, so the original document stays open and unchanged. JPEG quality runs from 0 (smallest file, most artifacts) to 12 (largest file, fewest artifacts). A value of 10 is a common default for photos on the web. STANDARDBASELINE is the most widely compatible JPEG encoding.
JPEG cannot store layers, so Photoshop writes a flattened version into the file. Your layered document is not changed.
What the script assumes about transparency
A PNG keeps transparency only if the document has transparent pixels. A document created with DocumentFill.WHITE has an opaque Background layer, so the PNG will have a white rectangle behind your content. Both of these fix that:
- Create the document with
DocumentFill.TRANSPARENT. - Convert an existing Background layer with
doc.activeLayer.isBackgroundLayer = false.
A JPEG has no transparency at all. Any transparent areas are filled with the matte color, which is white by default.
A batch example
This script converts every supported image in a folder to a JPEG in an out subfolder. It never saves over the originals.
// ExtendScript: batch-convert a folder of images to JPEG
function isImage(f) {
return f instanceof File && /\.(psd|jpe?g|png|tif|tiff)$/i.test(f.name);
}
var folder = Folder.selectDialog("Choose a folder of images");
if (folder) {
var files = folder.getFiles(isImage);
var outDir = new Folder(folder + "/out");
if (!outDir.exists) {
outDir.create();
}
var oldDialogs = app.displayDialogs;
app.displayDialogs = DialogModes.NO;
try {
for (var i = 0; i < files.length; i++) {
var doc = app.open(files[i]);
try {
if (doc.bitsPerChannel !== BitsPerChannelType.EIGHT) {
doc.bitsPerChannel = BitsPerChannelType.EIGHT;
}
var baseName = decodeURI(files[i].name).replace(/\.[^.]+$/, "");
var opts = new JPEGSaveOptions();
opts.quality = 10;
opts.embedColorProfile = true;
doc.saveAs(new File(outDir + "/" + baseName + ".jpg"), opts, true, Extension.LOWERCASE);
} finally {
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}
alert("Converted " + files.length + " file(s).");
} finally {
app.displayDialogs = oldDialogs;
}
}Several details in this script matter:
app.displayDialogs = DialogModes.NOsuppresses prompts such as the missing-profile and JPEG options dialogs, which would otherwise stop the batch. The script restores the old value in afinallyblock, so a crash does not leave dialogs off.doc.close(SaveOptions.DONOTSAVECHANGES)discards the bit-depth change and closes the file without prompting. Open documents pile up in memory if you skip this.File.nameis URI-encoded, so a space appears as%20.decodeURIrestores readable names.- A PSD with several layers is flattened in the JPEG output. Nothing is written back to the PSD.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "General Photoshop error occurred" on JPEG save | Document is 16-bit or 32-bit | Convert to 8 bits per channel first. |
| PNG has a white background | Background layer is opaque | Use a transparent fill, or unlock the Background layer. |
| Script stops on a dialog | Profile mismatch or options prompt | Set `app.displayDialogs = DialogModes.NO` and restore it afterward. |
| "Object is invalid" after a close | Using `doc` after `doc.close()` | Finish all work on the document before closing it. |
| Output saved to the wrong place | `~` or a relative path resolved differently than expected | Build paths from `Folder` objects, or print `file.fsName` to check them. |
| Original PSD renamed or overwritten | `asCopy` was `false` | Pass `true` unless you want Save As behavior. |
Limits of this approach
ExtendScript has no equivalent of Export As with its scale and metadata options. The saveAs options are close to Save As and Save a Copy. If you need resizing, add doc.resizeImage(width, height) before saving. For a bulk resize in a real project, run it on a duplicate or a copy of the file, because resizing a layered master is destructive.
Adobe is moving newer scripting work to UXP, which uses modern JavaScript. ExtendScript still runs in current Photoshop versions, and a large body of existing scripts depends on it.
Exercise
You run a script that creates a document with DocumentFill.WHITE, draws a logo on a new layer, and saves it with PNGSaveOptions. The logo should be on a transparent background, but the PNG has a white rectangle behind it. Name two changes that fix it, and say which argument keeps the open document unchanged after saving.
Show answer
Fix 1: create the document with DocumentFill.TRANSPARENT so no opaque Background layer exists. Fix 2: after creating it, unlock the Background layer with doc.backgroundLayer.isBackgroundLayer = false and delete or hide its white pixels. The asCopy argument (the third parameter of saveAs, set to true) keeps the open document tied to its original name and format.