Photoshop Automation via JavaScript

Introduction

Like everything else in Photoshop there are several ways to perform any task, including automation.   One of these is JavaScript and that is the foundation of this article.   I am using three Photoshop JavaScript utilities in my workflow that I would like to share.

The first, UpdatePsInfo simply allow me to add static data such as name and address to the Photoshop Information Panels.   This is propagated to standard metadata tags in other image formats such as TIF and JPG.

The second, ReSizeSample merely resizes an image for printing or web posting.   It has options for dealing with any potential change in the image aspect ratio.   It uses bicubic smoother if the size is being increased or bicubic sharper if the size is being decreased.   If the new size is a different aspect ratio than the image, there are options to expand the canvas, trim the image, or simply maintain the image aspect ratio.   Portrait or landscape orientation is automatically dealt with.

The third, CopyrightLayer adds a shape layer with a custom logo, icon, or signature.   Optionally it can add a text layer containing the base filename.   Both the custom shape and the text are automatically sized to match the image size and pixel resolution.

The Basics

You do not have to be a JavaScript expert to use these, but some tailoring will be necessary.   I have tried to limit this to a few variables at the top of each file.   And I have tried to document the code so that you can see how the scripts work.

To use the scripts you need to copy them to [PSInstall]/Presets/Scripts/.   If you are using CS1 the extension should be ".js".   If you are using CS2 the recommended extension would be ".jsx".   Do not rename "ReSizeCoreScript.jsxinc".   With CS2 you can double click on the script file and it will bring up the Extend Script editor.   With CS1 you simply use a text editor such as notepad.   To support multiple different options simply make copies with different names.

You will need to restart Photoshop so that it will find any new script(s).   These can now be run against an opened image with the PS File > Scripts menu.

For automation, you will want to incorporate the scripts in PS actions.   You can simply start a new action, give it a unique name, record a step that plays the script, and then stop recording.   You do not have to have an image opened for this.   The script will merely generate an alert and exit so that the step is recorded successfully.   The action can then be referenced in the automation tasks.

With CS1 the images may be selected from the File Browser.   The CS2 Bridge does not allow you to run an action that references a script.   So I recommend creating a source folder with only the images you want to update.   You can then run the action from Photoshop Automate > Batch selecting this folder as the source. For CS2 I also have an automation script GetFilesFromBridge that allows you to run multiple scripts or actions against the current Bridge selection.

The Photoshop CS scripting guides and references are available at the Adobe Site.   There are many good books on JavaScript available at most bookstores.   Just be aware that most of them are oriented toward HTML forms and the Photoshop run time environment does not support HTML.   It does include a number of Adobe specific JavaScript objects that will not be in the standard documentation.

Tailoring ReSizeSample

Customization is performed in variables defined at the start of the script.   This example is from the ReSizeSample.

The requirement for this script was that I found that I needed multiple actions for each common image size that I routinely use.   One to upsize and one to downsize.   One for portrait and one for landscape.   One for the batch environment and one for open documents.   And there were still choices to be made regarding how to address any changes in the aspect ratio.   I quickly found myself with as many as eight actions for each image size.

     // =====================================================
     // Application "Landscape" Size Target Values Here:
     var newDocWidth = 10;                        // The long side
     var newDocHeight = 8;                        // The short side
     var newDocUnits = Units.INCHES;              // INCHES or PIXELS
     var newDocAdjust = "expand";                 // crop, expand, or none
     var bgFillColor = [255,255,255];             // canvas fill color (RGB)
     var myActionSet = "RagsActions";             // Action Set
     var myPostAction = "";                       // Post-processing Action or null or
                               // keyword: "thumbNail" to save sm_[name].jpg thumbnail
     var myScriptName = "ReSizeExpand_8x10";      // this script name
     // =====================================================

All this does is resize an image, but it does it with some intelligence.   That is, it automatically handles portrait or landscape orientation, it sets the interpolation options to sharper/smoother if the new image is smaller/ larger, and it has options to handle aspect ratio changes as you desire.

For printing, you want to specify the document size in inches.   The script will honor the pixel resolution (PPI) of the image unless it is 72 or 96 PPI.   These are assumed to be web images, so the PPI is changed to 300 for printing.   I typically use 314 PPI for my Kodak 8500 and 288 PPI for my Epson 2200, so by default these are not changed.   For web images, specify the size in pixels.   The PPI will be unaffected.   I usually change it to 72 (without resampling) when I save the image as a JPG.

There are three options to handle the aspect ratio.   The first, none will simply maintain the original image aspect ratio.   This is what I use for web images.   The second, crop will trim only one of the height or width centered as needed thus the canvas will be at the desired aspect ratio.   Of course, some of the image will be lost.   The third option, expand will maintain the image aspect ratio but expand the canvas to be the desired print aspect ratio.   The expanded areas are filled with "bgFillColor".   Of course, if the image is already at the target aspect ratio, all of these options produce the same result, no change.

Tailoring UpdatePsInfo

All this script does is update fields in the Photoshop Info panels.   If an image already has a copyright, it will not be overridden.   If this script has already been run, it will not update any information.   You can add keywords with this, but they cannot be dynamically specified.

     // ===============================================
     var copyrightNotice = "";               // copyright text
     var ownerUrl = "http://www.myURL.com";  // copyright URL
     var title = "my Title Info";            // title or studio name
     var author = "my Name";                 // author
     var authorPosition = "myStudio";        // studio name
     var headline = "";                      // headline text
     var city = "Fort Worth";                // city
     var country = "USA";                    // country
     var provinceState = "Texas";            // provinceState
     var credit = "";                        // creator credit
     var newKeywords = new Array("");        // quoted keywords separated by commmas
     var useCrSymbol = true;                 // false to use "(c)"
     var showCameraSettings = true;          // show camera settings in description
     var myActionSet = "RagsBatch";          // Action Set
     var myPreAction = "";                   // PreProcessing Action or null
     var myPostAction = "";                  // PostProcessing Action or null
     var scriptName = "UpdatePsInfo";        // default script name (for CS1)
     // ===============================================

The field names should be self-evident.   Multiple keywords can be each enclosed in quotes and separated by commas as shown.   Both CS1 and CS2 support these items.  

The copyright information will be prefixed with a copyright symbol and the current year.   The copyright symbol is a special case.   CS1 uses the HTML code.   CS2 uses the actual copyright character.   I subsequently found out that some parsers don’t handle either correctly.   So I recommend setting this to false, which will use basic the string "(c)".   This works with any parser.

The "showCameraSettings" option will show the camera settings (if available) in the Description field.   This is the ISO, shutter, aperture, and calculated exposure value.   If there is already data in the description, this is skipped.

This also allows you to specify an open action, and/or a save action (pre and post actions).   These can be used if you want to be able to override open and close steps in the automation panels.   I don’t use these anymore, but I did leave them in the sample script.

Tailoring CopyrightLayer

This script will create a custom shape copyright, logo, or signature layer and optionally create a text layer with the base image filename.   It can also optionally add basic copyright information if it doesn’t already exist.   Last, there is an option to flatten the image layers if desired.   The final image will look something like this:

    // ======================================
    // Configuration Variables
    // ======================================
    var shapeName = "Copyright symbol";                  // null string or custom shape name to add copyright layer
    var shapeWidth  = 200.0;                             // custom shape width (pixels)
    var shapeHeight = 200.0;                             // custom shape height (pixels)
    var shapeColor = Array(245.0, 238.0, 27.0);          // custom shape color (r,g,b)
    var shapeOpacity = 100.0;                            // copyright shape layer opacity
    var fillImage = false;                               // fill image with copyright shape

    var showFileName = true;                             // true to add filename text
    var scaleFileNameText = 1.0;                         // text size scaling 1 = 100%
    var fileNameTextColor = Array(255.0, 255.0, 255.0);  // file name text color (r,g,b)

    var showImageDate = false;                           // true to add image date    - or -
    var showIPTCDesc = false;                            // true to add IPTC Description text
    var scaleIPTCText = 1.2;                             // text size scaling 1 = 100%
    var placeIPTCText = 0.05;                            // text position as percentage of image height (0 = same as CR)
    var IPTCTextColor = Array(0.0, 0.0, 0.0);            // IPTC description text color (r,g,b)

    var myCopyrightInfo = false;                         // true to add copyright info: IPTC metadata
    var crNotice = "myCopyrightStatement";               // user copyright information
    var crAuthor = "me";                                 // user author name
    var crOwnerURL = "http://myURL.com";                 // user URL

To create a shape layer, the first thing you will need to do is create a Photoshop Custom Shape.   This is basically a vector shape.   For testing, you can use any PS default shape such as "Copyright symbol".   There are several ways to approach this.

I use Corel Draw only because I am more familiar with it.   Then, I have to import the vector into Adobe Illustrator.   You could simply start with Adobe Illustrator.   From here, I simply copy and past into Photoshop as a new shape layer.   Then, using the shape tool you can save this as a custom shape and give it a name.  

You can also use the Photoshop pen tools to create a vector path.   Or you can write your own fancy signature on a clean sheet of paper with a felt tip pen.   Then scan this or take a photograph.   Open the image in Photoshop and make a selection of the text.   Then convert the text to a path.   Select this path with the pen tool.   With the shape tool, it can be used to create a shape layer and saved as a custom shape.

Do whatever floats your boat, you just need a custom shape.   Set "shapeName"=myNewShape and you are almost ready to go.

The shape will be filled with yellow and will have the emboss and drop shadow layer styles so it also should be visible against any background.

This script is going to size the text and custom shape based on the current image attributes.   So a reference point is needed.   This is assumed to be an 8x10 image at 300 PPI.   The default text size is 30 points at these image dimensions.   You should manually create a shape layer on a default canvas at these dimensions.   Make the shape the size that seems right to you.   Hold the shift key as you re-size to maintain the original aspect ratio.  

Once you have sized the shape, you need to use the PS measure tool to measure the height and width.   Or make the shape into a selection and use that to crop the image.   Either way, get the width and height in pixels.   The aspect ratio does not have to be square.   Set these values in "shapeWidth" and "shapeHeight".   You are ready to go.

The script should then resize the shape based on the actual image resolution (PPI) and the actual image size.   A smaller image will get a smaller shape.   But an 8x10 image will get the same sized shape at any resolution (PPI).

By default, the shape will be positioned 10% from the right and the text will be positioned 10% from the left.   Both will be positioned approximately 90% from the top.   Look for:

    shapePosT += initDocHeight * 0.90;      // shape: 90% from top
    shapePosR += initDocWidth * 0.90;       // 10% from right

If you set "fillImage=true" the shape will be sized to fill the image horizontally and placed in the center.   You can then use "shapeOpacity" to fade the layer transparancy like a watermark.

Set "showFileName=true" to show the filename in a text layer.   This will be in the bottom left of the image by default.   The text is white with a black “stroked” border so it should be visible against any background color.

Set "showIPTCDesc=true" to show the IPTC description in a text layer or "showImageDate=true" to show the image creation date.   This will be centered at the top of the image by default.   The text is black with a white “stroked” border so it should be visible against any background color.

Set "myCopyrightInfo=true" and include your copyright information to update the PS Info panels.  

Along with the resize scripts, I find this very useful for creating web images, contact sheets, and 4x6 proof prints.

Some Hints and Tips:

With these scripts you are able to use ACR to update the image settings such as exposure and contrast without even opening them in Photoshop proper.   With CS2 you can also straighten and crop before the image is processed.   Use the Bridge as a light table to select, preview, and rank or label the desired images.   Then select all the desired images and double click to open them in ACR in filmstrip mode.   Apply your settings and cropping as desired.   Then click done and all the Bridge metadata will be updated.   Do not click cancel or all your current updates will be lost.

Next, select the final images to be processed from the Bridge again and use Tools > Photoshop > Image Processor to open and convert them all to PSD or TIF.   These will be in a new sub folder by default.   Do not attempt to run any actions that reference scripts in this step.   They will fail.

You are now ready to use Photoshop > Automate > Batch to run these action/scripts against all images in this new folder.   Which scripts you want will depend on your ultimate objective.   I save a tempAction at the top of my action set.   This allows me to copy the steps from my other action sets and combine them to run them all in one automation sequence.

Closing

These scripts are provided as shareware with no warranty, but also no copyright.   You are free to use and modify them.   If you feel obliged to pay something, make a contribution to your favorite charity.   The sample scripts are available at this link in a ZIP file PsJsUtilities.zip.   These have been tested under Windows and Mac systems with CS1, CS2, and CS3.  

If you have any comments, or suggestions, I would welcome your input.   Please send me an  Email.


Rags Gardner
Rags Int., Inc.
204 Trailwood Drive
Euless, TX 76039
(817) 267-2554
Send Email
www.rags-int-inc.com
September 1, 2004
July 14, 2005
June 21, 2006
February 29, 2008

This page last updated on: Friday February 29 2008
You are visitor number 71,888 since 09/01/04