Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Adobe Photoshop > Technique

This chapter is from the book

Working with the Adobe Photoshop CS2 Object Model

This section contains information about using the objects in the Adobe Photoshop CS2 Object Model. For information on object models, see “Object model concepts” on page 7 and “Adobe Photoshop CS2’s Object Model” on page 9.

Using the Application object

This section describes how and when to use the Application object in a script. It also describes how to use some properties of the Application object.

You use the properties and methods of the Application object to work with Adobe Photoshop CS2 functionality and objects such as the following:

  • Global Adobe Photoshop CS2 settings or preferences, such as unit values or color settings. See “Setting application preferences” on page 32.
  • Documents— You can add or open documents and set the active document. See “Opening a document” on page 30 and “Setting the active object” on page 28.
  • Actions— You can execute actions created either via scripting or using the Actions palette in the Adobe Photoshop CS2 application.

You can use Application object properties to get information such as the following:

  • A list of fonts installed on the system:
    • var fontstInstalled = app.fonts
  • The amount of unused memory available to Adobe Photoshop CS2.
  • The location of the Presets folder.

Using the Document object

The Document object can represent any open document in Adobe Photoshop CS2. You can think of a Document object as a file; you can also think of it as a canvas. You work with the Document object to do the following:

  • Access script objects contained in the Document object, such as ArtLayer or Channel objects. See “Containment hierarchy” on page 8 and “Adobe Photoshop CS2’s Object Model” on page 9 for more information.
  • Manipulate a specific Document object. For example, you could crop, rotate or flip the canvas, resize the image or canvas, and trim the image. See “Manipulating a Document object” on page 35 for a demonstration.
  • Get the active layer. See “Setting the active layer” on page 29.
  • Save the current document. See “Saving a document” on page 31.
  • Copy and paste within the active document or between different documents. See “Understanding clipboard interaction” on page 46.

Manipulating a Document object

The following example demonstrates how to do the following:

  • Change the size of the image to 4 inches wide and 4 inches high.
  • Change the size of the document window (or canvas) to 5 inches high and 6 inches wide.
  • Trim the top and bottom of the image.
  • Crop the image.
  • Flip the entire window.
//this sample script assumes the ruler units have been
set to inches
docRef.resizeImage( 4,4 )
docRef.resizeCanvas( 4,4 )
docRef.trim(TrimType.TOPLEFT, true, false, true, false)

//the crop command uses unit values
//change the ruler units to pixels
app.preferences.rulerUnits =Units.PIXELS
docRef.crop (new Array(10,20,40,50), 45, 20, 20, 72)
docRef.flipCanvas(Direction.HORIZONTAL)

Working with layer objects

The Adobe Photoshop CS2 object model contains two types of layer objects:

  • ArtLayer objects, which can contain image contents and are basically equivalent to Layers in the Adobe Photoshop CS2 application.
  • Layer Set objects, which can contain zero or more ArtLayer objects.

When you create a layer you must specify whether you are creating an ArtLayer or a Layer Set object.

Creating an ArtLayer object

The following example demonstrates how to create an ArtLayer object filled with red at the beginning of the current document.

// Create a new art layer at the beginning of the current
document
var layerRef = app.activeDocument.artLayers.add()
layerRef.name = "MyBlendLayer"
layerRef.blendMode = BlendMode.NORMAL

// Select all so we can apply a fill to the selection
app.activeDocument.selection.selectAll

// Create a color to be used with the fill command
var colorRef = new SolidColor
colorRef.rgb.red = 255
colorRef.rgb.green = 100
colorRef.rgb.blue = 0

// Now apply fill to the current selection
app.activeDocument.selection.fill(colorRef)

The following example shows how to create a Layer Set object after the creating the first ArtLayer object in the current document:

// Get a reference to the first layer in the document
var layerRef = app.activeDocument.layers[0]

// Create a new LayerSet (it will be created at the
beginning of the // document)
var newLayerSetRef = app.activeDocument.layerSets.add()

// Move the new layer to after the first layer
newLayerSetRef.move(layerRef,
ElementPlacement.PLACEAFTER)

Referencing ArtLayer objects

When you create a layer in the Adobe Photoshop CS2 application (rather than a script), the layer is added to the Layers palette and given a number. These numbers act as layer names and do not correspond to the index numbers of ArtLayer objects you create in a script.

Your JavaScript will always consider the layer at the top of the list in the Layers palette as the first layer in the index. For example, if your document has four layers, the Adobe Photoshop CS2 application names them Background Layer, Layer 1, Layer 2, and Layer 3. Normally, Layer 3 would be at the top of the list in the Layers palette because you added it last. If your script is working on this open document and uses the syntax layers[0].select() to tell Adobe Photoshop CS2 to select a layer, Layer 3 will be selected. If you then you drag the Background layer to the top of the list in the Layers palette and run the script again, the Background layer is selected.

You can use the following syntax to refer to the layers by the names given them by the Application:

layers["Layer 3"].select() //using the collection name
and square brackets for the collection

Working with layer set objects

Existing layers can be moved into layer sets. The following example shows how to create a Layer Set object, duplicate an existing ArtLayer object, and move the duplicate object into the layer set.

In JavaScript you must duplicate and place the layer.

var layerSetRef = docRef.layerSets.add()
var layerRef =
docRef.artLayers[0].duplicate(layerSetRef,
   ElementPlacement.PLACEATEND)
layerRef.moveToEnd (layerSetRef)

Linking Layer Objects

Scripting also supports linking and unlinking layers. You link layers together so that you can move or transform the layers in a single statement.

var layerRef1 = docRef.artLayers.add()
var layerRef2 = docRef.artLayers.add()
layerRef1.link(layerRef2)

Look up link() in the Methods table of the ArtLayer object in Part 2 of this book. Additionally, look up add() in the Methods table of the ArtLayers object.

Applying styles to layers

Your script can apply styles to an ArtLayer object. To apply a style in a script, you use the applyStyle() method with the style’s name as an argument enclosed in straight double quotes.

Please refer to Adobe Photoshop CS2 Help for a list of styles and for more information about styles and the Styles palette.

The following example sets the Puzzle layer style to the layer named “L1.”

docRef.artLayers["L1"].applyStyle("Puzzle (Image)")

Look up applyStyle() in the Methods table of the ArtLayer object in Part 2 of this book.

Using the Text Item object

You can change an existing ArtLayer object to a text layer, that is, a Text Item object, if the layer is empty. Conversely you can change a Text Item object to an ArtLayer object. This “reverse” procedure rasterizes the text in the layer object.

The Text Item object is a property of the ArtLayer object. However, to create a new text layer, you must create a new ArtLayer object and then set the art layer’s kind property to LayerKind.TEXT.

To set or manipulate text in a text layer, you use the textItem object, which is also a property of the ArtLayer object.

Creating a Text Item object

The following examples create an ArtLayer object and then use the kind property to convert it to a text layer.

var newLayerRef = docRef.artLayers.add()
newLayerRef.kind = LayerKind.TEXT

See “Adobe Photoshop CS2’s Object Model” on page 9 for information on the relationship between ArtLayer objects and TextItem objects.

Also, look up the kind and TextItem properties of the ArtLayer object in Part 2 of this book.

Determining a layer’s kind

The following example uses an if statement to check whether an existing layer is a text layer.

if (newLayerRef.kind == LayerKind.TEXT)

Adding and manipulating text in a text item object

The following example adds and right-justify text in a text layer.

var textItemRef = artLayers["my text"].textItem
textItemRef.contents = "Hello, World!"
docRef.artLayers["my text"].textItemRef.justification =
   Justification.RIGHT

To familiarize yourself with this objects, properties, and methods, look up the TextItem property of the ArtLayer object in Part 2 of this book. To find the properties and methods you can use with a text layer, look up the TextItem object.

Working with Selection objects

You create a Selection object to allow your scripts to act only on a specific, selected section of your document or a layer within a document. For example, you can apply effects to a selection or copy the current selection to the clipboard.

The Selection object is a property of the Document object. In Part 2 of this book, look up selection in the Properties table for the Document object. Also, look up the select in the Methods table for the Selection object.

Creating and defining a selection

To create a selection, you use the select() method of the Selection object.

You define a Selection object by specifying the coordinates on the screen that describe the selection’s corners. Since your document is a 2-dimensional object, you specify coordinates using the x-axis and y-axis as follows:

  • You use the x-axis to specify the horizontal position on the canvas.
  • You use the y-axis to specify the vertical position on the canvas.

The origin point in Adobe Photoshop CS2, that is, x-axis = 0 and y-axis = 0, is the upper left corner of the screen. The opposite corner, the lower right, is the extreme point of the canvas. For example, if your canvas is 1000 × 1000 pixels, then the coordinate for the lower right corner is x-axis = 1000 and y-axis = 1000.

You specify coordinate points that describe the shape you want to select as an array, which then becomes the argument or parameter value for the select() method.

The following example assumes that the ruler units have been set to pixels and create a selection by:

  1. Creating a variable to hold a new document that is 500 × 500 pixels in size.
  2. Creating a variable to hold the coordinates that describe the selected area (that is, the Selection object).
  3. Adding an array as the selection variable’s value.
  4. Using the Document object’s selection property, and the Selection object’s select() method to select an area. The area’s coordinates are the selection variable’s values.
    var docRef = app.documents.add(500, 500)
    var shapeRef = [
       [0,0],
       [0,100],
       [100,100],
       [100,0]
    ]
    docRef.selection.select(shapeRef)
    

Stroking the selection border

The following example uses the stroke() method of the Selection object to stroke the boundaries around the current selection and set the stroke color and width.

Inverting selections

You can use the invert() method of the Selection object to a selection so you can work on the rest of the document, layer or channel while protecting the selection.

selRef.invert()

Expanding, contracting, and feathering selections

You can change the size of a selected area using the expand, contract, and feather commands.

The values are passed in the ruler units stored in Adobe Photoshop CS2 preferences and can be changed by your scripts. If your ruler units are set to pixels, then the following example will expand, contract, and feather by 5 pixels. See section “Setting application preferences” on page 32 for examples of how to change ruler units.

var selRef = app.activeDocument.selection
selRef.expand( 5 )
selRef.contract( 5 )
selRef.feather( 5 )

Filling a selection

You can fill a selection either with a color or a history state.

To fill with a color:

var fillColor = new SolidColor()
fillColor.rgb.red = 255
fillColor.rgb.green = 0
fillColor.rgb.blue = 0
app.activeDocument.selection.fill( fillColor,
ColorBlendMode.VIVIDLIGHT,
   25, false)

To fill the current selection with the tenth item in the history state:

selRef.fill(app.activeDocument.historyStates[9])

Loading and storing selections

You can store Selection objects in, or load them from, Channel objects. The following examples use the store() method of the Selection object to store the current selection in a channel named My Channel and extend the selection with any selection that is currently in that channel.

selRef.store(docRef.channels["My Channel"],
SelectionType.EXTEND)

To restore a selection that has been saved to a Channel object, use the load() method.

selRef.load (docRef.channels["My Channel"],
SelectionType.EXTEND)

See section “Understanding clipboard interaction” on page 46 for examples on how to copy, cut and paste selections.

Working with Channel objects

The Channel object gives you access to much of the available functionality on Adobe Photoshop CS2 channels. You can create, delete, and duplicate channels or retrieve a channel’s histogram and change its kind. See “Creating new objects in a script” on page 27 for information on creating a Channel object in your script.

You can set or get (that is, find out about) a Channel object’s type using the kind property. See “Understanding and finding constants” on page 16 for script samples that demonstrate how to create a masked area channel.

Changing channel types

You can change the kind of a any channel except component channels. The following example demonstrates how to change a masked area channel to a selected area channel:

channelRef.kind = ChannelType.SELECTEDAREA

Using the DocumentInfo object

In Adobe Photoshop CS2, you can associate information with a document by choosing File > File Info.

To accomplish this task in a script, you use the DocumentInfo object. The following example demonstrates how to use the DocumentInfo object to set the copyrighted status and owner URL of a document.

docInfoRef = docRef.info
docInfoRef.copyrighted = CopyrightedType.COPYRIGHTEDWORK
docInfoRef.ownerUrl = "http://www.adobe.com"

For information about other types of information (properties) you can associate with a document, look up the Properties table for the DocumentInfo object in Part 2 of this book.

Using history state objects

Adobe Photoshop CS2 keeps a history of the actions that affect documents. Each time you save a document in the Adobe Photoshop CS2 application, you create a history state; you can access a document’s history states from the History palette by selecting Window > History.

In a script, you can access a Document object’s history states using the HistoryStates object, which is a property of the Document object. You can use a HistoryStates object to reset a document to a previous state or to fill a Selection object.

The following example reverts the document contained in the variable docRef back to the form and properties it had when it was first saved. Using history states in this fashion gives you the ability to undo modifications to the document.

docRef.activeHistoryState = docRef.historyStates[0]

The example below saves the current state, applies a filter, and then reverts back to the saved history state.

savedState = docRef.activeHistoryState
docRef.applyMotionBlur( 20, 20 )
docRef.activeHistoryState = savedState

Using Notifier objects

You use the Notifier object to tie an event to a script. For example, if you would like Adobe Photoshop CS2 to automatically create a new document when you open the application, you could tie a script that creates a Document object to an Open Application event.

Using the PathItem object

To add a PathItem object, you create an array of PathPointInfo objects, which specify the coordinates of the corners or anchor points of your path. Additionally, you can create an array of SubPathInfo objects to contain the PathPoint arrays.

The following script creates a PathItem object that is a straight line.

//line #1--it's a straight line so the coordinates
//for anchor, left, and right
//for each point have the same coordinates
var lineArray = new Array()
   lineArray[0] = new PathPointInfo
   lineArray[0].kind = PointKind.CORNERPOINT
   lineArray[0].anchor = Array(100, 100)
   lineArray[0].leftDirection = lineArray[0].anchor
   lineArray[0].rightDirection = lineArray[0].anchor

   lineArray[1] = new PathPointInfo
   lineArray[1].kind = PointKind.CORNERPOINT
   lineArray[1].anchor = Array(150, 200)
   lineArray[1].leftDirection = lineArray[1].anchor
   lineArray[1].rightDirection = lineArray[1].anchor

var lineSubPathArray = new Array()
   lineSubPathArray[0] = new SubPathInfo()
   lineSubPathArray[0].operation =
ShapeOperation.SHAPEXOR
   lineSubPathArray[0].closed = false
   lineSubPathArray[0].entireSubPath = lineArray

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020