Thumbnail Generation with Photoshop and JavaScript

by Chadwick Wood
December 15th, 2008

A couple of weeks ago I wrote a post called Conditional Image Resizing with Photoshop and JavaScript that illustrated how to write a script to perform quick photo cleanup and resizing within a bounded area. Today I want to talk about a similar technique for generating thumbnail images. The fundamentals are the same, but the goal is slightly different. Recently I did some redesign work for Stephen Zagorski Architects that also involved the addition of a lot of new project pages to the website. Each project page has an area for viewing images from the project, using thumbnails to navigate through the collection of images.

The full-size images have differing dimensions, but each of the thumbnails is 60 pixels square, which means each image is going to have to be cropped in some way. Due to the volume of thumbnails I needed to produce, this was not a process I wanted to do by hand. So, I set out to write a script that does the following:

  • If the image is taller than it is wide, crop it to a square by cropping off of the bottom of the image. Otherwise, crop it to a square by cropping off equal amounts from the sides.
  • After cropping, resize the image to 60 pixels square.
  • Apply auto-contrast, then sharpen.
  • Save it as a jpeg for the web.

The decision on "what to crop" from the image is based on the assumption that the most relevant parts of portraits are usually at the top, and for landscape, the relevant parts are in the middle. Of course this isn't always the case, but I find it gives good results most of the time.

The code for the script is below. If you need to know more about how to get this script running with Photoshop, you should refer to my previous post on the topic.

doc = app.activeDocument;
doc.changeMode(ChangeMode.RGB);

var thumbDim = 60; // the dimension of the square

// crop to a big square, conditionally, based on dimensions
if (doc.height > doc.width) {
    doc.resizeCanvas(doc.width,doc.width,AnchorPosition.TOPCENTER);
}
else {
    doc.resizeCanvas(doc.height,doc.height,AnchorPosition.MIDDLECENTER);
}

// resize, then auto-contrast and sharpen
// specify that our units are in pixels, via creation of a UnitValue object
doc.resizeImage(UnitValue(thumbDim,"px"),null,null,ResampleMethod.BICUBIC);
doc.activeLayer.autoContrast();
doc.activeLayer.applySharpen();

// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true;

var newName = 'thumb-'+doc.name+'.jpg';

doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);