Adobe PHOTOSHOP CS 2.0 Scripting Guide

®
®
2
cs
Photoshop
Scripting Guide
Adobe
bbc
© Copyright 2005 Adobe Systems Incorporated. All rights reserved.
®
Scripting Guide for Windows® and Macintosh®.
NOTICE: All information contained herein is the property of Adobe Systems Incorporated. No part of this publication (whether in hardcopy or electronic form) may be reproduced or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written consent of Adobe Systems Incorporated. The software described in this document is furnished under license and may only be used or copied in accordance with the terms of such license.
This publication and the information herein is furnished AS IS, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies, makes no warranty of any kind (express, implied, or statutory) with respect to this publication, and expressly disclaims any and all warranties of merchantability, fitness for particular purposes, and noninfringement of third party rights.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization.
Adobe, the Adobe logo, Illustrator, and Photoshop are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Apple, Mac, and Macintosh are trademarks of Apple Computer, Inc., registered in the United States and other countries. Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and other countries. JavaScript and all Java-related marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. UNIX is a registered trademark of The Open Group. All other trademarks are the property of their respective owners.
All other trademarks are the property of their respective owners.
If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational content contained in this guide.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA.

Contents

1 Introduction ................................................................................................................................. 1
About this manual.......................................................................................................................................................................... 1
What is scripting? ........................................................................................................................................................................... 2
Why use scripting?......................................................................................................................................................................... 2
Why use scripts instead of Actions?......................................................................................................................................... 2
System requirements.................................................................................................................................................................... 3
Choosing a scripting language ................................................................................................................................................. 4
New Features ................................................................................................................................................................................... 5
2 Scripting basics ............................................................................................................................ 6
Introducing Objects....................................................................................................................................................................... 6
Writing Script Statements ........................................................................................................................................................... 7
Object Model Concepts ............................................................................................................................................................... 7
Photoshop CS2’s Object Model................................................................................................................................................. 8
Object Elements and Collections.............................................................................................................................................. 9
Object References ........................................................................................................................................................................11
Using Commands and Methods .............................................................................................................................................12
Using Variables..............................................................................................................................................................................13
Using Object Properties.............................................................................................................................................................18
Understanding Object Classes and Inheritance................................................................................................................19
Using Arrays ...................................................................................................................................................................................19
Documenting Scripts ..................................................................................................................................................................20
Using Long Script Lines..............................................................................................................................................................21
Creating a Sample Hello World Script...................................................................................................................................21
Using Operators............................................................................................................................................................................25
Using Conditional Statements.................................................................................................................................................26
Using Subroutines, Handlers and Functions......................................................................................................................29
Executing JavaScripts from AS or VBS ..................................................................................................................................31
Passing AS or VBS Arguments to JavaScript.......................................................................................................................31
Testing and Troubleshooting ..................................................................................................................................................32
Bibliography...................................................................................................................................................................................34
3 Scripting Photoshop CS2 .......................................................................................................... 36
Viewing Photoshop CS2 Objects, Commands and Methods .......................................................................................36
Targeting and Referencing the Application Object.........................................................................................................37
Creating New Objects in a Script............................................................................................................................................37
Setting the Active Object ..........................................................................................................................................................39
Opening a Document .................................................................................................................................................................42
Saving a Document .....................................................................................................................................................................44
Setting Application Preferences ............................................................................................................................................46
Allowing or Preventing Dialogs ..............................................................................................................................................46
Working with the Photoshop CS2 Object Model..............................................................................................................47
Working with Color Objects .....................................................................................................................................................63
Working with Filters ....................................................................................................................................................................65
Understanding Clipboard Interaction ..................................................................................................................................66
Working with Units ......................................................................................................................................................................68
iii
Adobe Illustrator CS2
Visual Basic Scripting Reference Contents iv
Sample Workflow Automation JavaScripts.........................................................................................................................71
Advanced Scripting .....................................................................................................................................................................72
Index ...........................................................................................................................................85
1

Introduction

About this manual

This manual provides an introduction to scripting Adobe® Photoshop CS2® on Mac OS® and Windows®. Chapter one covers the basic conventions used in this manual and provides an overview of requirements for scripting Photoshop CS2.
Chapter two covers the Photoshop CS2 object model as well as generic scripting terminology, concepts and techniques. Code examples are provided in three languages:
AppleScript
VBScript
JavaScript
Note: Separate reference manuals are available for each of these languages and accompany this Scripting
Guide. The reference manuals are located on the installation CD.
Chapter three covers Photoshop CS2-specific objects and components and describes advanced techniques for scripting the Photoshop CS2 application.
Note: Please review the README file shipped with Photoshop CS2 for late-breaking news, sample scripts,
and information about outstanding issues.

Conventions in this guide

Code and specific language samples appear in monospaced courier font:
app.documents.add
Several conventions are used when referring to AppleScript, VBScript and JavaScript. Please note the following shortcut notations:
AS stands for AppleScript
VBS stands for VBScript
JS stands for JavaScript
The term “commands” will be used to refer both to commands in AppleScript and methods in VBScript and JavaScript.
When referring to specific properties and commands, this manual follows the AppleScript naming convention for that property and the VBScript and JavaScript names appear in parenthesis. For example:
display dialogs (DisplayDialogs/displayDialogs) property is part of the Application
“The object.”
In this case, VBScript property and
For larger blocks of code, scripting examples are listed on separate lines.
display dialogs refers to the AppleScript property, DisplayDialogs refers to the
displayDialogs refers to the JavaScript property.
1
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Introduction 2
AS
layer 1 of layer set 1 of current document
VBS
appRef.ActiveDocument.LayerSets(1).Layers(1)
JS
app.activeDocument.layerSets[0].layers[0]
Finally, tables are sometimes used to organize lists of values specific to each scripting language.

What is scripting?

A script is a series of commands that tells Photoshop CS2 to perform a set of specified actions, such as applying different filters to selections in an open document. These actions can be simple and affect only a single object, or they can be complex and affect many objects in a Photoshop CS2 document. The actions can call Photoshop CS2 alone or invoke other applications.
Scripts automate repetitive tasks and are often used as a creative tool to streamline tasks that might be too time consuming to do manually. For example, you could write a script to generate a number of localized versions of a particular image or to gather information about the various color profiles used by a collection of images.

Why use scripting?

While graphic design is characterized by creativity, some aspects of the actual work of illustration and image manipulation are anything but creative. Scripting helps creative professionals save time by automating repetitive production tasks such as resizing or reformatting documents.
Any repetitive task is a good candidate for a script. Once you can identify the steps and conditions involved in performing the task, you’re ready to write a script to take care of it.

Why use scripts instead of Actions?

If you’ve used Photoshop CS2 Actions, you’re already familiar with the enormous benefits of automating repetitive tasks. Scripting allows you to extend those benefits by allowing you to add functionality that is not available for Photoshop CS2 Actions. For example, you can do the following with scripts and not with actions:
You ca n add conditional logic, so that the script automatically makes “decisions” based on the current
situation. For example, you could write a script that decides which color border to add depending on the size of the selected area in an image: “If the selected area is smaller than 2 x 4 inches, add a green border; otherwise add a red border.”
A single script can perform actions that involve multiple applications. For example, depending on the
scripting language you are using, you could target both Photoshop CS2 and another Adobe Creative Suite 2 Application, such as Illustrator
You can open, save, and rename files using scripts.
®
CS2, in the same script.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Introduction 3
You can copy scripts from one computer to another. If you were using an Action and then switched
computers, you’d have to recreate the Action.
Scripts provide more versatility for automatically opening files. When opening a file in an action, you
must hard code the file location. In a script, you can use variables for file paths.
Note: See Photoshop CS2 Help for more information on Photoshop CS2 Actions.

System requirements

Any system that runs Photoshop CS2 supports scripting.

Mac OS

You can create AppleScripts or JavaScripts for use with Photoshop CS2 on a Macintosh system.
AppleScript Requirements
You can create AppleScripts on a Macintosh using the Script Editor application, which is installed as part of your Mac OS in the Applications/AppleScript folder. If Script Editor is not on your system, you can install it from your original system software CD-ROM.
You also need AppleScript, which is installed automatically with the OS. If for any reason AppleScript technology has not been installed on your system, you can install it as well from your system software CD-ROM.
Note: As your scripts become more complex, you may want to add debugging and productivity features
not found in the Script Editor. There are many third-party script editors that can write and debug Apple Scripts. For details, check http://www.apple.com/applescript.
For more information on the AppleScript scripting environment, see ‘Viewing Photoshop CS2’s
AppleScript Dictionary’ on page 36.
This manual uses the Script Editor from Apple for creating AppleScripts. For more information on using Script Editor, see ‘Creating and Running an AppleScript’ on page 22
JavaScript Requirements (Mac OS)
You can create JavaScripts using any text editor that allows you to save your scripts in a text format with a
.jsx extension.
The editor applications that are part of a default Apple OS installation, Script Editor and TextEdit, do not allow you to create and save JavaScript files. However, your Mac OS installation CD includes the Developer application Project Builder, which you can use to create JavaScripts.

Windows

.
You can create VBScript scripts on a Windows platform using any text editor that allows you to save your scripts in a text format with a
For more information, see ‘Creating and Running a VBScript’ on page 23
.vbs extension.
.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Introduction 4

JavaScript

You can write JavaScripts on either the Mac OS or Windows platform using any text editor. You must save JavaScript files as text files with a
.jsx extension.
For more information, see ‘Creating and Running a JavaScript’ on page 24

Choosing a scripting language

Your choice of scripting language is determined by two trade-offs:
1. Do you need to run the same script on both Macintosh and Windows computers?
If yes, you must create a JavaScript. See ‘Cross-platform scripts’ on page 4
2. Does the task you are scripting involve multiple applications (such as Photoshop CS2 and Illustrator CS2 or a database program)?
If yes, you must create an AppleScript if you are using a Macintosh; you must create a VBScript script if you are using Windows. See ‘Scripts that control multiple applications’ on page 5
Tip: You can combine JavaScript’s versatility with the platform-specific advantages of using either
AppleScript or VBScript by executing JavaScripts from your AppleScripts or VBScript scripts. See
‘Executing JavaScripts from AS or VBS’ on page 31
Note: You can use other scripting languages, although they are not documented in this manual.
On Mac OS, you can use any language that allows you to send Apple events.
On Windows, you can use any OLE Automation-aware language.
.
.
.
for more information.
Legacy OLE Automation scripting
Photoshop CS2 supports legacy Automation scripting as long as you modify the way that you refer to the Photoshop CS2
Set appRef = CreateObject("Photoshop.Application")
you must change the above code to read:
Set appRef = CreateObject("Photoshop.Application.9.1")
No other change is necessary for legacy COM scripts to run under Photoshop CS2.
Application object in your scripts. For example, instead of saying:

Cross-platform scripts

Because JavaScripts performs identically on both Windows and Macintosh computers, it is considered a cross-platform scripting language.
You run a JavaScript from within Photoshop CS2 by storing the script in the ...Presets\Scripts folder of your Photoshop CS2 installation and then selecting the script from the File > Scripts menu.
Running JavaScripts from within Photoshop CS2 eliminates the scripts’ facility to directly address other applications. For example, you cannot easily write a JavaScript to manage a workflow that involves Photoshop CS2 and a database management program.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Introduction 5

Scripts that control multiple applications

You can write scripts in either AppleScript or VBScript that control multiple applications. For example, on a Macintosh you can write an AppleScript that first manipulates a bitmap in Photoshop and then commands a web design application to incorporate it. You can write a script with similar capability on Windows using VBScript as the scripting language.

New Features

The scripting interface now allows you to do any of the following:
Specify Camera Raw options when opening a document.
Optimize documents for the Web.
Create and format contact sheets.
Specify options for the Batch command.
Apply the Lens Blur filter.
Automatically run scripts when specified events occur. For example, using a notifier object, you can
associate a script with an event such as the Photoshop CS2 application opening, so that the script runs whenever the application opens.
2

Scripting basics

This chapter provides a brief introduction to the basic concepts and syntax of the scripting languages AppleScript, VBScript, and JavaScript. If you are new to scripting, you should read this entire chapter.
If you are familiar with scripting or programming languages, you most likely will want to skip many sections in this chapter. Use the following list to locate information that is most relevant to you.
For more information on Photoshop CS2’s object model, see ‘Photoshop CS2’s Object
Model’ on page 8.
For information on selecting a scripting language, see ‘Choosing a scripting language’ on
page 4.
For examples of scripts created specifically for use with Photoshop CS2, see Chapter 3, ‘Scripting
Photoshop CS2’ on page 36.
For detailed information on Photoshop CS2 objects and commands/methods, please refer to the
following publications, which are located on the installation CD in the same directory as this Guide:
Adobe Photoshop CS2 AppleScript Scripting Reference
Adobe Photoshop CS2 Visual Basic Scripting Reference
Adobe Photoshop CS2 JavaScript Scripting Reference

Introducing Objects

A script is a series of commands that tell Photoshop CS2 what to do. Basically, the commands manipulate objects.
What are objects in the context of a scripting language? When you use Photoshop CS2, you create documents, layers, channels, and design elements, and you can work with a specific area of an image by selecting the area. These things are objects. The Photoshop CS2 application is also an object.
Each type of object has its own properties and commands (AppleScript) or methods (VBScript and JavaScript).
Properties describe or characterize the object. For example:
A layer object has a background color. It can also have a text item.
A channel object has color properties such as red, green, and blue.
The selected area of an image, or selection object, has size and shape properties.
Commands and methods describe actions you want to take on the object. For example, to print a document, you use the
Note: For more detailed information on commands and methods, see
on page 12.
When you write a script to manipulate an object, you can use only the properties and commands or methods defined for that object. For example, a Channel object does not, obviously, have a
print/PrintOut/print() command/method.
How do you know which properties or commands/methods you can use? Adobe provides all the information you need in the following references, which are available on the installation CD:
Document object’s print/PrintOut/print() command/method.
‘Using Commands and Methods’
Adobe Photoshop CS2 AppleScript Scripting Reference
6
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 7
Adobe Photoshop CS2 Visual Basic Scripting Reference
Adobe Photoshop CS2 JavaScript Scripting Reference
Tip: Throughout this guide, explanations of how to create a script for a task are followed by instructions
for looking up in the appropriate scripting reference the specific elements used in the script. Using these instructions will help you quickly understand how to script Photoshop CS2.

Writing Script Statements

A scripting language, like human languages, uses sentences or statements, for communication. To write a script statement:
Name an object.
Name the property you want to change or create.
Indicate the task you want to perform on the object’s property. In AppleScript, you use a command. In
VBScript and JavaScript, you use a method.
For example, to create a new document called myDocument, you would write a script statement that says
Add a document called myDocument
In this example, the object is document, its “name” property is myDocument, and the command or method is add.

Syntax

Because you use scripting languages to communicate with the your computer, you must follow strict rules that the computer can understand. These rules are called the language’s syntax.
The syntaxes for AppleScript, VBScript, and JavaScript are different. In this guide, you will learn basic scripting concepts that these languages share. You will also learn some of the syntax that is specific to each language.

Object Model Concepts

In a script statement, you refer to an object based on where the object is located in an object model. An object model is simply an arrangement of objects. The arrangement is called a containment hierarchy.
Here’s a way to think about object models:
1. You live in a house, which we will think of as your
2. The house has rooms, which we will call its
3. Each room has
Windows can be open or shut. (In other words, a whether or not the window is open.)
If you want to write a script that opens a window in your house, you would use the property or command/method that accomplishes the task. But first, you need to identify the window. This is where the object model comes in: you identify the window by stating where it is in the careful arrangement of objects contained in your house.
First of all, the window is contained by the house. But there are lots of windows, so you need to provide more detail, such as the room in the house. Again, there is probably more than one window in each room, so you’d also need to provide the wall that the window is in. Using the house object model, you would identify the window you want to open as "the window on the north wall in the living room in my house".
window and door objects.
house object.
room objects.
window object has an open property that indicates
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 8
To get the script to open that window, you’d simply add the command or method for opening it. Thus your scripting statement would look like this:
In my house, in the living room, the window on the north wall: open it.
Similarly, you could create a script in your house model to change the color of a door to blue. In this case, you might be able to use the
In my house, in the bedroom, the door to the bathroom: blue.
door object’s color property instead of a command or method:

Containment Hierarchy

When we refer to an object model as a containment hierarchy, we mean that we identify objects in the model partially by the objects that contain them. You can picture the objects in the house model in a hierarchy, similar to a family tree, with the house on top, rooms at the next level, and the windows and doors branching from the rooms.

Applying the Concept to Photoshop CS2

Now apply this object model concept to Photoshop CS2. The Photoshop CS2 application is the house, its documents are the rooms, and the layers, layersets, channels, and selected areas in your documents are the windows, doors, ceilings, and floors. You can tell Photoshop CS2 documents to add and remove objects or set or change individual object properties like color, size and shape. You can also use commands or methods, such as opening, closing, or saving a file.

Photoshop CS2’s Object Model

To create efficient scripts, you need to understand the containment hierarchy of the Photoshop CS2 object model.
.
Object Model Classes
Selection
Path Item
Path Point
Channel
Histogram
Array
Application
Document
Art Layer
Text Item
(Object)
Art Layer
Layer Set
Document
Info
Layer Set
Notifier
History
State
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 9
The following table provides information about each object.
To create this object without
Object Name Description
Application The Photoshop CS2 application Start the Photoshop CS2
using a script:
application.
Document The working object, in which you create layers,
channels, actions, and so on. In a script, you name, open, or save a document as you would a file in the application.
Selection The selected area of a layer or document. Choose the marquee or lasso
Path Item A drawing object, such as the outline of a shape or a
straight or curved line
Channel Pixel information about an image’s color Choose Window > Channels.
Art Layer A layer class within a document that allows you to
work on one element of an image without affecting other elements in the image.
Layer Set A collection of
Document Info Metadata about a
Note: Metadata is any data that helps to describe
the content or characteristics of a file, such filename, creation date and time, author name, the name of the image stored in the file, etc.
Art Layer objects. Choose Layer > New >
Document object.
In Photoshop CS2, choose File > New or File > Open.
tools and drag your mouse.
Choose the path selection or pen tools and draw a path with the mouse.
Choose Layer > New > Layer or Window > Layers.
Layer Set.
Choose File > File Info.
Notifier Notifies a script when an event occurs; the event
then triggers the script to execute. For example, when a user clicks an OK button, the notifier object tells the script what to do next.
History State Stores a version of the document in the state the
document was in each time you saved it.
Note: You ca n use a
Selection object or to reset the document
to a previous state.
History State object to fill a

Object Elements and Collections

When you add an object to your script, the object is included automatically in an object element (AppleScript) or collection (VBScript, JavaScript). The objects in a single element or collection are identical types of objects. For example, each collection; each
Art Layer object belongs to an Art Layers element or collection.
Channel object in your script belongs to a Channels element or
Choose File > Scripts > Script Events Manager.
Choose Window > History,
and then choose a history state from the History palette.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 10
Note: Your scripts place objects in elements or collections even when there is only one object of that type
in the entire script, that is, only one object in the element or collection.
When you add an object, the object is numbered automatically within its respective element or collection. You can identify the object in other script statements by using its element or collection name and assigned number.
Using the house example, when you add a room to your house, your script stores a number that identifies the room. If it’s the first room you’ve added, your AppleScript considers the room to be room1; your VBScript script or JavaScript considers the room to be room0.
Here’s how the scripting languages handle the automatic numbering if you add a second room:
AppleScript considers the new room room1 and renumbers the previously added room so that it
becomes room2. AppleScript object numbers shift among objects to indicate the object that you worked with most recently. See the AppleScript section in
Element or Collection’ on page 10 for further details on this topic.
VBScript or JavaScript numbers are static; they don’t shift when you add a new object to the collection.
‘Referring to an Object in an
Object numbering in VBScript and JavaScript indicates the order in which the objects were added to the script. Because the first room you added was considered room0, the next room you add is considered room1; if you add a third room, it is labeled room2.
When you add an object that is not a room, the numbering starts all over for the new object element or collection. For example, if you add a door, your AppleScript considers the door to be door1; your VBScript script or JavaScript considers the door door0.
Note: You can also name objects when you add them. For example, you can name the rooms livingRoom
and bedRoom. If an object has a name, you can refer to the object in your script either by name or by the element/collection name followed by the assigned number.
Generally, beginning scripters are encouraged to use object names in AppleScript.
In VBScript or JavaScript, you’ll find object numbers very useful. For example, you may have several files in which you want to make the background layer white. You can write a script that says "Open all files in this folder and change the first layer’s color to white." If you didn’t have the capability of referring to the layers by number, you’d need to include in your script the names of all of the background layers in all of the files. Chances are, if you created the files using the Photoshop CS2 application rather than a script, the layers don’t even have names.

Indexes or Indices

An object’s number in an element or collection is called an index.

Referring to an Object in an Element or Collection

A collection or element name is the plural version of the object type name. For example, an element or collection of name and the index to refer to an object. The syntax is slightly different in AppleScript.
The following code samples demonstrate the correct syntax for using an object’s index when referring to the object.
Document objects is called documents. In JavaScript and VBScript, you can use the collection
Tip: Remember that VBScript and JavaScript indices begin with 0. Beginning your count with 0 may seem
confusing, but as you learn about scripting, you’ll find that using 0 gives you added capabilities for getting your scripts to do what you want.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 11
AS
In AppleScript, you use the object type name followed by a space and then the index. The following statement refers to the current document. Notice that the element name is implied rather than used explicitly.
document 1
Note: If the element name were used, this statement would be document 1 of documents.
AppleScript abbreviates the syntax by inferring the element name from the object type name.
In AppleScript, the number that refers to an object in an element changes when the script manipulates other objects. Unless you update the older art layer’s status to “active layer”, references made to
layer 1
of current document refer to the new layer.
art
Note: See
Tip: For beginning scripters, it’s a good idea to name all objects in your AppleScripts and then refer to the
‘Setting the Active Object’ on page 39 for more information about selecting the active
layer.
objects by name.
VBS
In VBScript, you use the collection name followed by the index enclosed in parentheses. There is no space between the collection name and the parentheses.
Documents(1)
JS
In JavaScript, the collection name is followed by the index in square brackets with no space between the object name and the brackets.
documents[0]

Object References

Because scripts use a containment hierarchy, you can think of an object reference as being similar to the path to a file.
You can use an object’s name or index to refer to the object. (See
The following code samples demonstrate the syntax for referring to an which was the first layer added to the layer added to the current document:
‘Indexes or Indices’ on page 10.)
artLayer object named Profile,
layerSet object named Silhouettes, which in turn was the first
AS
Object index reference:
layer 1 of layer set 1 of current document
Object name reference:
layer "Profile" of layer set "Silhouettes" of current document
Note: When you refer to an object by name, you must enclose the name in double quotes ("").
You can also combine the two types of syntax:
layer 1 of layer set "Silhouettes" of current document
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 12
VBS
Object index reference:
appRef.ActiveDocument.LayerSets(0).Layers(0)
Object name reference:
appRef.ActiveDocument.LayerSet("Silhouettes").Layer(“Profile”)
You can also combine the two types of syntax:
appRef.ActiveDocument.LayerSets(1).Layer(“Profile”)
Tip: Notice that when you refer to an object by its assigned name you use the object classname, which is
singular ( collection name, which is plural (
LayerSet or Layer). When you use a numeric index to refer to an object, you use the
LayerSets or Layers).
JS
Object index reference:
app.documents[1].layerSets[0].layers[0]
Object name reference:
appRef.document(“MyDocument”).layerSet("Silhouettes").layer(“Profile”)
You can also combine the two types of syntax:
appRef.activeDocument.layerSet("Silhouettes").layers[0]
Note: When you refer to an object by its assigned name you use the object classname, which is singular
document or layerSet or layer). When you use a numeric index to refer to an object, you use
( the collection name, which is plural (

Using Commands and Methods

Commands (in AppleScript) and methods (in VBScript and JavaScript) are directions you add to a script to perform tasks or obtain results. For example, you could use the to open a specified file.
Note: You can use only the methods or commands associated with that object type. For example, you can
use the object which, obviously, cannot be opened.
Before using a command on an AppleScript object, look up either the object type or the
Before using a method on a VBScript or JavaScript object, look up the method in the Methods
open/Open/open() command/method on a Document object but not on a Selection
command in the Adobe Photoshop CS2 AppleScript Scripting Reference to be sure the association is valid.
For example, you could look up you could look up the
Document object in the “Objects” chapter.
open in the “Commands” chapter of the scripting reference; or
table for the object type in the Adobe Photoshop CS2 Visual Basic Scripting Reference or the Adobe Photoshop CS2 JavaScript Scripting Reference.
For example, you could look up the the object’s Methods table.
documents or layerSets or layers).
open/Open/open() command/method
Document object in the “Interface” chapter, and then find

Commands and Command Properties

Commands (AppleScript) use normal English sentence syntax. The script statement begins with an imperative verb form followed by a reference to the object upon which you want the script to perform the task. The following AppleScript command prints the first layer of the current document:
print layer 1 of current document
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 13
Some commands require additional data. In AppleScript, the make new command adds a new object. You can specify properties for the object by enclosing the properties in brackets and preceding the brackets with the phrase with properties. The following statement creates a new document that is four inches wide and two inches high.
make new document with properties {width:4 as inches, height:2 as inches}
Note: See ‘Setting the Active Object’ on page 39 for information on making sure your script
performs the task on the correct object.

Methods and Arguments

You insert methods at the end of a VBScript or JavaScript statement. You must place a period before the method name to separate it from the rest of the statement.
The following VBScript statement prints the current document:
appRef.Documents(1).PrintOut
A method in JavaScript must be followed by parentheses, as in the following statement:
app.documents[0].print()
Some methods require additional data, called arguments, within the parentheses. Other methods have optional arguments. The following statements use the named myDocument that is 4000 pixels wide and 5000 pixels tall and has a resolution of 72 pixels per inch:
Add/add() method to add a bitmap document
Note: Even though the
(myDocument), you use the object collection name when you add the object. See
an Object in an Element or Collection’ on page 10 for more information on object
collections. See versus object names in a singular form.
VBS
appRef.Documents.Add(4000, 5000, 72, "myDocument", 5)
Note: The enumerated value 5 at the end of the script statement indicates the value psNewBitmap for
the constant contains detailed information about enumerated values and constants.
JS
app.documents.add(4000, 5000, 72, "myDocument", DocumentMode.BITMAP)

Using Variables

A variable is a container for data you use in your script. For example, in the following AppleScript statements the variables new document.
Document object in the following script statements is given a name
‘Referring to
‘Object References’ on page 11 for information on object collection names
PsNewDocumentMode. The Adobe Photoshop CS2 Visual Basic Scripting Reference
docWidth and docHeight replace the width and height specifications for the
Without variables:
make new document with properties {width:4 as inches, height:2 as inches}
With variables:
set docWidth to 4 inches set docHeight to 2 inches make new document with properties {docWidth, docHeight}
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 14

Why Use Variables?

There are several reasons for using variables rather than entering values directly in the script.
Variables make your script easier to update or change. For example, if your script creates several 4 x 2
inch documents and later you want to change the documents’ size to 4 x 3 inches, you could simply change the value of the variable
docHeight from 2 to 3 at the beginning of your script and the entire
script would be updated automatically.
If you had used the direct value 2 inches to enter the height for each new document, updating the document sizes would be much more tedious. You would need find and change each statement throughout the script that creates a document.
Variables make your scripts reusable in a wider variety of situations. As a script executes, it can assign
data to the variables that reflect the state of the current document and selection, and then make decisions based on the content of the variables.

Data Contained in Variables

The data that a variable contains is the variable’s value. To assign a value to a variable, you use an assignment statement. A variable’s value can be a number, a string (a word or phrase or other list of
characters enclosed in quotes), an object reference, a mathematical expression, another variable, or a list (including collections, elements, and arrays).
‘Using Operators’ on page 25 for information on using mathematical expressions or other
See variables as values. See
Assignment statements require specific syntax in each scripting language. See
and Assigning Values’ on page 14 for details.
‘Using Object Properties’ on page 18 for information about arrays.
‘Creating Variables

Creating Variables and Assigning Values

This section demonstrates how to create two variables named thisNumber and thisString, and then assign the following values:
Variable Value
thisNumber
thisString
Note: When you assign a string value to a variable, you must enclose the value in straight, double quotes
(""). The quotes tell the script to use the value as it appears without interpreting or processing it. For example, 2 is a number value; "2" is a string value. The script can add, subtract, or perform other operations with a number value. It can only display a string value.
AS
In AppleScript, you must both create and assign a value to a variable in a single statement. You can create a variable using either the
With the set command, you list the variable name (called an identifier in AppleScript) first and the value second, as in the following example:
set thisNumber to 10 set thisString to "Hello, World"
With the copy command, you list the value first and the identifier second.
copy 10 to thisNumber copy "Hello World" to thisString
set command or the copy command.
10
"Hello World"
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 15
Using the Variable in a Script
After declaring and assigning values to your variables, you use the variables in your script to represent the value; you use only the variable name without the
display dialog command to create a dialog box with the text Hello World.
the
display dialog thisString
set or copy command. The following statement uses
Assigning an Object Reference as a Value
You can also use variables to store references to objects. (See ‘Object References’ on page 11 for an explanation of object references.) The following statement creates a variable named its value, creates a new
Art Layer object. When you use thisLayer in a script statement, you are
thisLayer and as
referring to the new layer.
set thisLayer to make new art layer in current document
You can also assign a reference to an existing object as the value:
set thisLayer to art layer 1 of current document
AppleScript Value Types
You can use the following types of values for variables in your AppleScripts.
Note: For now, don’t worry about the value types you don’t understand.
Value Type What It Is Sample Value
boolean
integer
Logical true or false. true
Whole numbers (no decimal
14 points). Integers can be positive or negative.
real
A number that may contain a
13.9972
decimal point.
string
A series of text characters.
"I am a string"
Note: Strings appear inside
(straight) quotation marks.
list
An ordered list of values. The
{10.0, 20.0, 30.0, 40.0} values of a list may be any type.
object
record
A specific reference to an object. current document
An unordered list of properties,
{name: "you", index: 1} Each property is identified by its label.
VBS
To create a variable in VBScript, you use the Dim keyword at the beginning of the statement. The following statements create the variables
Dim thisNumber Dim thisString
You can declare multiple variables in a single Dim statement by separating the variables with a comma (,), as follows:
Dim thisNumber, thisString
thisNumber and thisString.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 16
To assign a value to a variable, you use the equals sign (=), as follows:
thisNumber = 10 thisString = "Hello, World"
Note: Remember to enclose string values in straight, double quotes ("").
Another rule of thumb for proper scripting in VBScript is to declare all of your variables somewhere near the beginning of the script. That way you can easily see which variables are in use without having to search throughout the script for them.
The VBScript tool
Option Explicit forces you to declare all variables before you use them in a script
statement. It also helps you avoid situations in which you try to use a misspelled variable name or an undeclared variable. You use
Option Explicit before you declare any variables, as in the following
code sample:
Option Explicit Dim thisNumber Dim thisString thisNumber = 10 thisString = "Hello, World"
Assigning an Object Reference as a Value
You assign an object reference as the value of a variable, use the Set command as well as the equal sign. The following example uses
Layer
object, and then assign the new Art Layer object as the value of thisLayer:
Dim thisLayer Set thisLayer = AppRef.Documents(0).ArtLayers.Add
Set and the Add method to create the variable thisLayer, create a new Art
The next example uses Set to assign an existing Art Layer object (in this case, the third Art Layer object added to the script) as the value of
Dim thisLayer Set thisLayer =AppRef.Documents(0).ArtLayers(2)
thisLayer:
Using the Variable in a Script Statement
When you use variables in your script to represent values, you use only the variable name without the Dim
Set keyword. The following example rotates the selected section of the Art Layer object
or represented by the variable
thisLayer.Selection.Rotate(45)
thisLayer by 45 degrees:
VBScript Value Types
You can use the following types of values for variables in VBScript.
Note: For now, don’t worry about the value types you don’t understand.
Value Type What It Is Example
Boolean
Logical true or false true
false
Empty
Error
Null
The variable holds no data myVar = Empty
Stores an error number
The variable holds no valid
null value (Usually used to test an error condition)
Number
Any number not inside double quotes
3.7
2000
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 17
Value Type What It Is Example (Continued)
Object
Properties and methods belonging to an object or
activeDocument
Documents(1).ArtLayers(2) array
String
A series of text characters. Strings appear inside (straight) quotation marks
"Hello"
"123 Main St."
" "
JS
The var keyword declares (that is, creates) variables in JavaScript. The following example uses separate statements to declare and assign a value to the variable assigned and declared in a single statement.
var thisNumber thisNumber = 10 var thisString = "Hello, World"
To assign a reference to an object in JavaScript, you use the same syntax as other JavaScript assignment statements:
var docRef = app.activeDocument
JavaScript Value Types
You can use the following types of values for variables.
Note: For now, don’t worry about the value types you don’t understand.
thisNumber; the variable thisString is
Value Type What It Is Examples
String
Number
Boolean
Null
Object
Function
Undefined

Naming Variables

A series of text characters that appear inside (straight) quotation marks
Any number not inside double quotes
"Hello"
"123 Main St."
" "
3.7
15000
Logical true or false true
Something that points to nothing
Properties and methods belonging to an object or array
Value returned by a function
activeDocument
Documents(1).artLayers(2)
See ‘Using Subroutines,
Handlers and Functions’
on page 29.
Devoid of any value undefined
It’s a good idea to use descriptive names for your variables—such as firstPage or corporateLogo, rather than names only you would understand and that you might not recognize when you look at your
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 18
script a year after you write it, such as x or c. You can also give your variable names a standard prefix so that they’ll stand out from the objects, commands, and keywords of your scripting system. For example, you could use the prefix “doc” at the beginning of any variables that contain to identify variables that contain
Variable names must be a single word (no spaces). Many people use internal capitalization (such as
myFirstPage) or underscore characters (my_first_page) to create more readable names.
Variable names cannot begin with a number or contain punctuation or quotation marks.
Art Layer objects.
Document objects, or “layer”
You can use underscore characters ( _ ), but not as the first character in the name.
Variable names in JavaScript and VBScript are case sensitive. thisString is not the same as
thisstring or ThisString.
Variable names in AppleScript are not case sensitive.

Using Object Properties

Properties describe an object. For example, a Document object’s height and width properties describe the document’s size.
To access and modify a property of an object, you name the object and then name the property. The specific syntax varies by language. The following examples use the kind property of the to make the layer a text layer.
ArtLayer object
AS
You can specify properties using with properties at the end of the statement and enclosing the properties in brackets ({ }). Within the brackets, you name the property and then type a colon (:) and the property definition after the colon, as in the following sample.
make new art layer with properties {kind:text}
VBS
In VBScript, you use an object’s property by naming the object, then typing a period (.), and then typing the property. Use the equals sign (=) to set the property value.
Set layerRef toArtLayers.Add layerRef.Kind = 2
Note: The Kind property value, 2, is a constant value. VBScript uses the enumerated constant values
rather than the text version of the value. To find constant values, refer to the “Constants’ chapter in the appropriate scripting reference. For more information, see
Constants’ on page 19.
‘Understanding and Finding
JS
In JavaScript, you name the object, type a period (.), and then name the property, using the equals sign (=) to set the property value.
var layerRef = artLayers.add() layerRef.kind = LayerKind.TEXT
Note: The kind property in JavaScript uses a constant value indicated by the upper case formatting. In
JavaScript, you must use constant values exactly as they appear in the scripting language reference. To find constant values, refer to the “Constants’ chapter in the appropriate scripting reference. For more information, see
‘Understanding and Finding Constants’ on page 19.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 19

Understanding and Finding Constants

Constants are a type of value that defines a property. Using the example of the kind property of an Art
Layer
object, you can define only specific kinds that Photoshop CS2 allows.
In JavaScript, you must use constants exactly as they are defined—with the exact spelling and capitalization. In VBScript, you use a constant’s enumerated value.
Note: Throughout this document, actual values of enumerations are given using the following format:
newLayerRef.Kind = 2 '2 indicates psLayerKind --> 2 (psTextLayer)
The ' before the explanation creates a comment and prevents the text to the right of the ' from being read by the scripting engine. For more information, see Documenting Scripts information on comments.
A constant is indicated as a hypertext link in the Value Type column of the Properties table in the scripting language reference. When you click the link, you can view the list of possible values for the property.
For example, look up the
Art Layer object in the “Interface” chapter of any of the following references
on the installation CD:
Adobe Photoshop CS2 Visual Basic Scripting Reference
Adobe Photoshop CS2 JavaScript Scripting Reference
for more
In the Properties table, look up the values you can use to define the
kind. The Value Type column for kind contains a link. Click the link to view
kind property.
Note: Different objects can use the same property with different constant values. The constant values for
Channel object’s kind property are different than the constant values for the Art Layer
the object’s
kind property.

Understanding Object Classes and Inheritance

In Photoshop CS2, every type of object— document, layer, etc.—belongs to its own class, each with its own set of properties and behaviors.
Object classes may also “inherit,” or share, the properties of a parent, or superclass. When a class inherits properties, we call that class a child or subclass of the class from which it inherits properties. In Photoshop CS2,
Classes can have properties that aren’t shared with their superclass. Using an example from our house object, both window objects and door objects might inherit an "opened" property from the parent
Opening class, but a window could have a numberOfPanes property which the Opening class could not
have.
In Photoshop CS2 for example, from the
Layer class.
When you use the scripting language reference documents included on the installation CD, if you encounter the term inherited from, it indicates that the object class you are looking at is a child class of the parent class named in the definition.
Art Layer objects, for example, inherit from the Layer class.
Art Layer objects have the property grouped which is not inherited

Using Arrays

In VBScript and JavaScript, arrays are similar to collections; however, arrays are not created automatically.
You can think of an array as a list of values for a single variable. For example, the following JavaScript array lists 4 values for the variable
var myFiles = new Array () myFiles[0] = “clouds.bmp”
myFiles:
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 20
myFiles[1] = “clouds.gif” myFiles[2] = “clouds.jpg” myFiles[3] = “clouds.pdf”
Notice that each value is numbered. To use a value in a statement, you must include the number. The following statement opens the file
open(myFiles[1])
clouds.gif:
The following sample includes the same statements in VBScript:
Dim myFiles (4) myFiles(0) = “clouds.bmp” myFiles(1) = “clouds.gif” myFiles(2) = “clouds.jpg” myFiles(3) = “clouds.pdf”
appRef.Open myFiles(1)

Documenting Scripts

You can document the details of your script by including comments throughout the script. Because of the way they are formatted, comments are ignored by the scripting system as the script executes.
Comments help clarify (to humans, including yourself) what your script does. It is generally considered good programming practice to document each bit of logic in your script.
You use comments to:
Help you remember the purpose of a section of your script.
Help you remember to include all the components you planned for your script. Unless you are an
experienced programmer, you can review your script by reading through the comments more easily than you can by reading the code.
Help others understand your script. It’s possible that other people in your organization will need to use,
update, or debug your script.

Comment Syntax

You can create the following types of comments:
Single-line: An entire line is a comment and therefore ignored when your script runs.
End-of-line: The line begins with executable code, then becomes a comment which is ignored when
the script runs.
Multi-line: An entire block of text, which runs more than a single line in your script, is a comment.
The following sections demonstrate how to format comments in your scripts.
AS
To enter a single-line or end-of-line comment in an AppleScript, type two hyphens (--) before the comment.
-- this is a single-line comment set thisNumber to 10 --this is an end-of-line comment
To include a multi-line comment, start your comment with a left-parenthesis followed by an asterisk ( (* ) and end with an asterisk followed by a right-parenthesis ( *) ), as in the following example.
(* this is a multi-line comment *)
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 21
Note: Generally, your scripts are easier to read if you format all comments as single-line comments
because the comment status of the line is indicated at the beginning of the line.
VBS
In VBScript, enter a single straight quote ( ' ) to the left of the comment.
' this is a comment Dim thisString ' this is an end-of-line comment
Note: VBScript does not support multi-line comments. To comment out more than one line, begin each
line with a single straight quote.
JS
In JavaScript, use the double forward slash to comment a single or partial line:
// This comments until the end of the line var thisString = "Hello, World" // this comments until the end of the line as well
Enclose multi-line comments in the following notation /* */.
/* This entire block of text is a comment*/
Note: Generally, your scripts are easier to read if you format all comments as single-line comments
because the comment status of the line is indicated at the beginning of the line.

Using Long Script Lines

In some cases, individual script lines are too long to fit on a single line in your script editor window.
AS
AppleScript uses the special character (¬) to show that the line continues to the next line. This continuation character denotes a “soft return” in the script. Press Option-Return to type the character.
VBS
In VBScript, use a space followed by an underscore ( _).
JS
JavaScript does not require a line continuation character. When an individual statement is long to fit on a single line, the next line simply wraps to the following line. However, to make your script easier to read, you can use the space bar or Tab to indent the continuation line.
Note: You can put more than one JavaScript statement on a single line if you separate the statements with
a semicolon ( Here is an example of putting two statements on a single line:
var thisNumber= 10; var thisString = "Hello, World"
;). However, your scripts are easier to read if you start a new line for each statement.

Creating a Sample Hello World Script

It’s time to put the scripting concepts you’ve just learned into practice. Traditionally, the first thing to accomplish in any programming environment is the display of a "Hello World" message.
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 22
Our Hello World scripts will do the following:
1. Open the Photoshop CS2 application.
2. Create a new
When we create the document, we will also create a variable named reference to the document as the value of
Document object.
docRef and then assign a
docRef. The document will be 4 inches wide and 2 inches
high.
3. Create an
In our script, we will create a variable named
Layer
4. Define
Art Layer object.
artLayerRef and then assign a reference to the Art
object as the value of artLayerRef.
artLayerRef as a text item.
5. Set the contents of the text item to "Hello World".
Note: We will also include comments throughout the scripts. In fact, because this is our first script, we will
use comments to excess.
These steps mirror a specific path in the containment hierarchy, as illustrated below.
Application
Document

Creating and Running an AppleScript

You must open Apple’s Script Editor application in order to complete this procedure.
Note: The default location for the Script Editor is Applications > AppleScript > Script Editor.
To create and run your first Photoshop CS2 AppleScript:
1. Enter the following script in the Script Editor:
Art Layer
Text Item
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 23
Note: The lines preceded by “--” are comments. Entering the comments is optional.
-- Sample script to create a new text item and
-- change its contents.
--target Photoshop CS2 tell application "Adobe Photoshop CS2"
-- Create a new document and art layer. set docRef to make new document with properties ¬
{width:3 as inches, height:2 as inches}
set artLayerRef to make new art layer in docRef
-- Change the art layer to be a text layer. set kind of artLayerRef to text layer
-- Get a reference to the text object and set its contents. set contents of text object of artLayerRef to "Hello, World"
end tell
2. Click Run to run the script. Photoshop CS2 creates a new document, adds a new layer, changes the layer’s type to text and sets the text to “Hello, World”
Note: If you encounter errors, see
‘AppleScript Debugging’ on page 32

Creating and Running a VBScript

Follow these steps to create and run a VBScript that displays the text Hello World! in a Photoshop CS2 document.
To create and run your first Photoshop CS2 VBScript:
1. Type the following script into a script or text editor.
Note: Entering comments is optional.
Dim appRef Set appRef = CreateObject( "Photoshop.Application" )
' Remember current unit settings and then set units to ' the value expected by this script Dim originalRulerUnits originalRulerUnits = appRef.Preferences.RulerUnits appRef.Preferences.RulerUnits = 2
' Create a new 4x4 inch document and assign it to a variable. Dim docRef Dim artLayerRef Dim textItemRef Set docRef = appRef.Documents.Add(4, 4)
' Create a new art layer containing text Set artLayerRef = docRef.ArtLayers.Add artLayerRef.Kind = 2
' Set the contents of the text layer. Set textItemRef = artLayerRef.TextItem textItemRef.Contents = "Hello, World!"
' Restore unit setting appRef.Preferences.RulerUnits = originalRulerUnits
Photoshop CS2
Adobe Photoshop CS2 Scripting Guide Scripting basics 24
2. Save file as a text file with a .vbs file name extension.
3. Double-click the file in Windows Explorer to run the script.
The script opens Photoshop CS2.

Creating and Running a JavaScript

Follow these steps to create and run a JavaScript that displays the text Hello World! in a Photoshop CS2 document.
Because you will be actually using Photoshop CS2 to run your JavaScripts, it is not necessary to include code that opens Photoshop CS2 at the beginning of the script.
Note: Adobe has created the Extend Script scripting language to augment JavaScript for use with
Photoshop CS2. You can use the Extend Script command application and create the ability to open JavaScripts that manipulate Photoshop CS2 from anywhere in your file system. See the “Script UI” chapter of the Adobe Photoshop CS2 JavaScript Scripting Reference for more information.
To create and run your first Photoshop CS2 JavaScript:
1. Type the following script.
#target to target the Photoshop CS2
Note: Entering comments is optional.
// Hello Word Script // Remember current unit settings and then set units to // the value expected by this script var originalUnit = preferences.rulerUnits preferences.rulerUnits = Units.INCHES
// Create a new 4x4 inch document and assign it to a variable var docRef = app.documents.add( 4, 4 )
// Create a new art layer containing text var artLayerRef = docRef.artLayers.add() artLayerRef.kind = LayerKind.TEXT
// Set the contents of the text layer. var textItemRef = artLayerRef.textItem textItemRef.contents = "Hello, World"
// Release references docRef = null artLayerRef = null textItemRef = null
// Restore original ruler unit setting app.preferences.rulerUnits = originalUnit
2. Save file as a text file with a .jsx file name extension in the Presets > Scripts folder in your Adobe Photoshop CS2 directory.
Note: You must place your JavaScripts in the Presets > Scripts folder in order to make the scripts
accessible from the File > Scripts menu in Photoshop CS2. The scripts do not appear on the File > Scripts menu until you restart the application.
Note: Photoshop CS2 also supports JavaScript files that use a
.js extension.
Loading...
+ 63 hidden pages