Sub topic 13
Automating resizes with a script
Earlier chapters used the Image Size and Canvas Size dialogs by hand. This chapter shows how to run the same operations from an ExtendScript file, so you can apply them to a whole folder of images. It assumes you can already predict what Resample on and off do, you know what an anchor point does in Canvas Size, and you can run a .jsx file from File > Scripts > Browse.
Which dialog maps to which method
Each dialog has a matching method on the Document object. The method arguments are the dialog fields.
| Dialog action | Script call | Notes |
|---|---|---|
| Image Size, Resample on | `doc.resizeImage(width, height, resolution, method)` | Adds or removes pixels. |
| Image Size, Resample off | `doc.resizeImage(undefined, undefined, ppi, ResampleMethod.NONE)` | Relabels the print size and leaves the pixels alone. |
| Canvas Size | `doc.resizeCanvas(width, height, anchor)` | Changes the working area and does not scale the artwork. |
| Crop tool with no resample | `doc.crop([left, top, right, bottom])` | Bounds are in the current ruler units. |
| Free Transform on a layer | `layer.resize(horizontalPercent, verticalPercent, anchor)` | Scales one layer by percentages. |
The mapping above is the reason to decide which command you need before you write any code. The decision from the earlier chapter still applies. Use resizeImage to change how many pixels there are, resizeCanvas to change the space around the pixels, and crop to discard pixels you do not want.
Set the ruler units first
resizeImage and resizeCanvas take UnitValue objects, and Photoshop interprets bare numbers using app.preferences.rulerUnits. Likewise, doc.width.value returns a number in whatever unit the ruler is set to. A script that assumes pixels will give wrong results on a machine where the ruler is set to inches or centimeters.
The safe pattern has three steps:
- Save the user's current unit.
- Set
Units.PIXELS. - Restore the original unit in a
finallyblock, so an error cannot leave the user's preferences changed.
var originalUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
try {
// work here
} finally {
app.preferences.rulerUnits = originalUnits;
}Resizing a single image
The next function scales the long edge to a target size and keeps the proportions. It never enlarges an image, because upsampling invents pixels and a batch job should not do that silently.
function fitLongEdge(doc, maxEdge, ppi) {
var w = doc.width.value;
var h = doc.height.value;
var scale = maxEdge / Math.max(w, h);
if (scale >= 1) {
return false; // already small enough, do not upsample
}
var newW = Math.round(w * scale);
var newH = Math.round(h * scale);
doc.resizeImage(
UnitValue(newW, "px"),
UnitValue(newH, "px"),
ppi,
ResampleMethod.BICUBICSHARPER
);
return true;
}Computing both dimensions yourself, and rounding them, gives you predictable pixel counts. If you pass only a width, Photoshop does not always keep the proportions for you in a script. This is the same arithmetic as the dialog's linked chain icon, and in a script you do it explicitly.
Choosing the interpolation constant
The ResampleMethod constants correspond to the interpolation choices in the dialog.
| Constant | Typical use |
|---|---|
| `NEARESTNEIGHBOR` | Pixel art and hard-edged graphics where edges must stay crisp. |
| `BILINEAR` | Fast, low-quality scaling. |
| `BICUBIC` | General purpose, smooth gradients. |
| `BICUBICSMOOTHER` | Enlarging photos. |
| `BICUBICSHARPER` | Reducing photos. This is the usual choice for downsampling. |
| `BICUBICAUTOMATIC` | Lets Photoshop choose between smoother and sharper based on the direction of the resize. |
| `NONE` | No resampling. Only the resolution changes. |
A batch job often contains both large and small files. If you use BICUBICAUTOMATIC, you do not have to branch on the scale factor yourself.
Changing resolution without touching pixels
To mark a file as 300 ppi without altering pixel data, pass undefined for width and height and use ResampleMethod.NONE:
var doc = app.activeDocument;
doc.resizeImage(undefined, undefined, 300, ResampleMethod.NONE);A 3000 px wide image then reports a width of 10 in. If you had passed ResampleMethod.BICUBIC instead, the pixel count would have changed to keep the old print size. That is the scripted version of leaving Resample on. This is a common error, and it is easy to miss because the call still succeeds.
Extending the canvas from a script
The following call adds 100 px on each side and keeps the artwork centered:
doc.resizeCanvas(
UnitValue(doc.width.value + 200, "px"),
UnitValue(doc.height.value + 200, "px"),
AnchorPosition.MIDDLECENTER
);The anchor argument works like the grid in the dialog. TOPLEFT keeps the top-left corner fixed, so all the new space is added on the right and bottom. BOTTOMCENTER keeps the bottom edge fixed and centers horizontally.
You cannot pass an extension color to resizeCanvas. The new area behaves like the dialog's default. On a Background layer, it is filled with the current background color. On a regular layer, it is transparent. To control the color, set it before the call:
var white = new SolidColor();
white.rgb.red = 255;
white.rgb.green = 255;
white.rgb.blue = 255;
app.backgroundColor = white;If you want a transparent margin, convert the Background layer to a normal layer first. You can do that by setting doc.activeLayer.isBackgroundLayer = false, but only when the active layer is the Background layer.
A complete batch script
This script asks for a folder, resizes every JPEG, PNG, or TIFF file so its long edge is at most 1600 px, and saves JPEG copies in a resized subfolder. The originals are never overwritten.
#target photoshop
var MAX_EDGE = 1600;
var OUTPUT_PPI = 72;
function isImage(f) {
return f instanceof File && /\.(jpe?g|png|tiff?)$/i.test(f.name);
}
function fitLongEdge(doc, maxEdge, ppi) {
var w = doc.width.value;
var h = doc.height.value;
var scale = maxEdge / Math.max(w, h);
if (scale >= 1) {
return false;
}
doc.resizeImage(
UnitValue(Math.round(w * scale), "px"),
UnitValue(Math.round(h * scale), "px"),
ppi,
ResampleMethod.BICUBICSHARPER
);
return true;
}
var originalUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
try {
var inFolder = Folder.selectDialog("Choose the folder to resize");
if (inFolder) {
var outFolder = new Folder(inFolder.fsName + "/resized");
if (!outFolder.exists) {
outFolder.create();
}
var files = inFolder.getFiles(isImage);
var jpg = new JPEGSaveOptions();
jpg.quality = 10;
for (var i = 0; i < files.length; i++) {
var doc = app.open(files[i]);
try {
doc.bitsPerChannel = BitsPerChannelType.EIGHT;
fitLongEdge(doc, MAX_EDGE, OUTPUT_PPI);
doc.flatten();
var base = files[i].name.replace(/\.[^.]+$/, "");
doc.saveAs(new File(outFolder.fsName + "/" + base + ".jpg"), jpg, true, Extension.LOWERCASE);
} finally {
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}
alert("Processed " + files.length + " file(s).");
}
} finally {
app.preferences.rulerUnits = originalUnits;
}Some details in this script are there to prevent common failures:
doc.close(SaveOptions.DONOTSAVECHANGES)sits in afinallyblock, so one bad file does not leave documents open.doc.flatten()is called before saving because JPEG has no layers or transparency.bitsPerChannelis set to 8 because JPEG cannot store 16-bit data.- The output goes to a separate folder, so running the script twice cannot resample an already-resampled file.
- Resizing from the original file each time, never from a previous output, avoids the repeated-resampling quality loss covered in the Smart Objects chapter.
Scripting edge cases
- Smart Objects.
doc.resizeImageresamples the whole document, including the rasterized pixels of a layer. To scale one Smart Object layer non-destructively, uselayer.resize(percentX, percentY, AnchorPosition.MIDDLECENTER). The source pixels inside the Smart Object stay untouched. - Rounding. Passing fractional pixel values makes Photoshop round them in ways you did not choose. Round yourself.
- Document units in the Image Size dialog. The dialog's unit menus are separate from
rulerUnits, so a script that sets the ruler to pixels does not change what the dialog shows. - Large batches. For many files, wrap the work in an Action with File > Automate > Batch, or use Image Processor. A script gives you more control, such as skipping files that are already small.
- History. Scripted changes appear as history states. For a single large document, you can group many calls into one state with
doc.suspendHistory("Resize", "myFunction()").
Exercises
Exercise
A 4800 x 3200 px image is open. You run doc.resizeImage(undefined, undefined, 300, ResampleMethod.NONE). What are the pixel dimensions and the print size afterward?
Show answer
The pixel dimensions stay 4800 x 3200 because nothing is resampled. The print size becomes 4800 / 300 = 16 in by 3200 / 300 = about 10.67 in.
Exercise
You want to add a 50 px margin only to the bottom of an image, with the artwork staying at the top. Write the resizeCanvas call, assuming rulerUnits is Units.PIXELS.
Show answer
doc.resizeCanvas(doc.width, UnitValue(doc.height.value + 50, "px"), AnchorPosition.TOPCENTER); The TOPCENTER anchor keeps the top edge fixed, so all 50 px of new space appears at the bottom.
Exercise
Why does the batch script write to a separate "resized" folder and check scale >= 1 before resizing?
Show answer
The separate folder keeps the originals intact and prevents a second run from resampling already-resized files, which would lose quality. The scale check avoids upsampling small images, which would add invented pixels without adding detail.