TweetFollow Us on Twitter

Introduction to Scripting Photoshop

Volume Number: 22 (2006)
Issue Number: 8
Column Tag: AppleScript Essentials

Introduction to Scripting Photoshop

by Benjamin S. Waldie

Over the past several months, we have focused on scriptable ways to interact with remote directories using applications like Fetch, Transmit, Cyberduck, and more. Now, we're going to switch gears a bit, and begin to discuss something that pertains more to the creative side of the Macintosh market. We're going to begin looking at scriptable graphics programs. This month's column will provide an introduction to scripting Photoshop, the professional-level image editing application from Adobe.

First, a bit of history. Interestingly, Photoshop did not support AppleScript automation natively until version 7. Prior to this, however, users were able to automate Photoshop 5 and 6 with the use of PhotoScripter, a third-party plug-in from Main Event Software <http://www.mainevent.com/>. With the release of Photoshop 7, although Photoshop now supported AppleScript, this support was not installed by default. Rather, users were required to run a second installer from Adobe, in order to add scripting support. Since that time, Photoshop's scripting support has continued to grow with each new release, as the application implements new features and options. Today, Photoshop's scripting support is installed automatically, and has become a vital part of countless users' automated workflows.

Before we get started with writing code, I should mention that all of the examples in this month's column were written and tested with Photoshop CS2, version 9.0. If you are using a different version of Photoshop, please be aware that certain terminology may differ from that which I am using. In order to ensure that you are using the proper terminology, be sure to consult Photoshop's AppleScript dictionary.

Benefits of Scripting Photoshop

Regular Photoshop users often question the need for using AppleScript to drive Photoshop, since many automation technologies are actually built into the application itself. Photoshop's built-in actions palette will allow users to record manual tasks, to be triggered later at a click of the mouse in order to automate time-consuming and repetitive processes. Photoshop even contains a batch capability, which can allow users to automatically process complete folders full of files at once.

Yet, AppleScript automation of Photoshop has many benefits. For one, Photoshop actions don't contain logic, i.e. if this situation occurs, then do this one thing, if this other situation occurs, then do this other thing. AppleScripts, on the other hand, can be written to analyze situations, and take different courses of action based on situations that are encountered during processing. Furthermore, an AppleScript can be written to trigger Photoshop actions, making it possible to utilize a combination of AppleScript and built-in recorded actions in order to achieve more complex types of automation. Another thing that AppleScript can do, which Photoshop's built-in automation cannot do, is interact with other applications on your machine. AppleScripts, for example, can be written to do things such as go into QuarkXPress, extract a list of images, open those images in Photoshop, process them, and import them into Quark again.

As you can see, there are a number of benefits to using AppleScript to drive Photoshop. Now, let's start writing some code.

Getting Started

Opening Images

When scripting Photoshop, one of the first things that you will probably want to do is open an image. This can be done by using the open command. For example:

set theImage to choose file with prompt "Please select an image file:"
tell application "Adobe Photoshop CS2"
   open theImage
end tell

When opening images in Photoshop via AppleScript, one thing to keep in mind is that in certain circumstances, dialogs may be displayed, requesting user input. Figure 1 shows an example of a dialog that could be displayed when attempting to open an EPS file.



Figure 1. A Photoshop Open Dialog Window

If a dialog is displayed in Photoshop when attempting to open an image with AppleScript, this can actually cause your script to hang, as it will be waiting for a reply from Photoshop indicating that the document was successfully opened. With a dialog opened in Photoshop, this reply will never come, and your script will eventually time out. To try to ensure that this type of situation does not occur, it is usually a good idea to utilize the showing dialogs parameter of the open command. This parameter may be used to prevent dialogs from being displayed when opening a file. For example:

tell application "Adobe Photoshop CS2"
   open theImage showing dialogs never
end tell

Although they may appear when opening problematic files, dialogs are usually displayed during the open process when attempting to open certain types of files, such as EPS files, as we have seen above, PDF files, or Camera RAW files. The reason for this is because Photoshop will allow you to specify various options for how the file is handled as it is opened. Suppose you want to open a multi-page PDF, for example. To do so, you would need to indicate to Photoshop which page of the PDF to display. You may want to specify other options as well, such as resolution.

Just as in manual processing, when writing a script that will open a file, you may not always want to bypass open options for certain types of files. Rather, you may want to specify the options that should be used. To do this, you may use the with options parameter of the open command, and specify the open options for the type of file being opened. A list of scriptable open options can be found in the Open Formats Suite of Photoshop's AppleScript dictionary. See figure 2.



Figure 2. PDF Open Options

The following example code demonstrates the proper usage of the open command, while specifying options for opening an EPS file.

set theImage to choose file with prompt "Please select an EPS file:"
tell application "Adobe Photoshop CS2"
   open theImage with options {class:EPS open options, constrain proportions:false, 
      use antialias:false, mode:RGB, resolution:300} showing dialogs never
end tell

Modifying Application Settings

Before we begin working with opened images in Photoshop, I want to mention that many of Photoshop's preferences are accessible with AppleScript. These settings are accessible via the settings property of Photoshop's application class.

One such modifiable setting is Photoshop's unit of measurement, i.e. pixels, inches, centimeters, etc. You cannot assume that the user running your script is using the same units of measurement that you are. Since many scriptable image manipulation techniques in Photoshop require that you provide unit values, it is necessary to ensure that the correct unit type is being used. For example, suppose you have written a script that will resize an image to 800 x 600 pixels. If Photoshop's units of measurement were set to inches, you would end up with one extremely large resized image.

The following example code demonstrates how you could go about changing Photoshop's units of measurement to the type required by your script, in this case, pixels.

tell application "Adobe Photoshop CS2"
   set ruler units of settings to pixel units
end tell

Working with Images

Now that you know how to open an image in Photoshop, you will likely want to begin processing it. To do so, you will need to reference the image in some way. This is done via the document class. Unfortunately, Photoshop doesn't subscribe to the common front to back numeric ordering scheme that most applications do. In other words, as you will find, document 1 will not always be the front document. Because of this, you will probably want to refer to a document by name. For example:

tell application "Adobe Photoshop CS2"
   tell document "My Document.eps"
      -- Do something
   end tell
end tell

That said, if you only have one document opened, then it is safe to refer to the document numerically. For example:

tell application "Adobe Photoshop CS2"
   tell document 1
      -- Do something
   end tell
end tell

Accessing the Current Image Document

The open command in Photoshop does not produce a result, such as a reference to the newly opened document. Therefore, after opening a document, you will probably want to retain a reference to it. Assuming that the newly opened document is the front document, which it should be, you can retrieve a reference to it by accessing the current document property of the application class. For example:

tell application "Adobe Photoshop CS2"
   set theDocument to current document
end tell
--> document "My Document.eps" of application "Adobe Photoshop CS2"

Accessing Image Document Properties

In Photoshop, documents possess a wide variety of properties, many of which are read only. Regardless, utilizing document properties is an important part of scripting. For example, you might want to retrieve the height, width, and resolution of a document, in order to determine whether the document needs to be resized, cropped, or otherwise.

The following example code demonstrates how to retrieve the height of a document. Notice that its result is returned using the current unit of measurement, which, in this case, is pixels.

tell application "Adobe Photoshop CS2"
   tell theDocument
      height
   end tell
end tell
--> 3300.0

To retrieve the width of a document, access its width property. For example:

tell application "Adobe Photoshop CS2"
   tell theDocument
      width
   end tell
end tell
--> 2550.0

It is also possible to dynamically convert unit of measurement values to the desired type. For example, the following code will retrieve the width of a document, in inches, regardless of Photoshop's current units of measurement setting.

tell application "Adobe Photoshop CS2"
   tell theDocument
      width as inches
   end tell
end tell
--> 8.5

To retrieve the resolution of a document, you may access its resolution property, as shown in the example code below.

tell application "Adobe Photoshop CS2"
   tell theDocument
      resolution
   end tell
end tell
--> 300.0

We have just scratched the surface regarding dealing with document properties. Documents possess many other properties, which I encourage you to explore further in Photoshop's AppleScript dictionary.

Accessing File Info

In Photoshop, documents may also possess what is known as file information. This information, once applied, will stay with many types of files, once saved, and may be extracted or displayed by other applications. File information could be a document author, copyright information, a description, etc.

A document's file information may be modified via AppleScript. This is done with the use of the info property of the document class. The following example code will apply an author name, URL, and copyright information to the file information of a document.

tell application "Adobe Photoshop CS2"
   tell theDocument
      tell info
         set author to "Ben Waldie"
         set owner url to "http://www.automatedworkflows.com"
         set copyrighted to copyrighted work
         set copyright notice to "Copyright 2006, Ben Waldie, Automated Workflows, LLC"
      end tell
   end tell
end tell

In Photoshop, file information for a document may be viewed by selecting File Info... from the File menu. Figure 3 shows an example of the file information window for a document.



Figure 3. File Info for a Document

It is also possible to retrieve the file information of a document via AppleScript. The following code demonstrates how to retrieve the author of a document from its file information.

tell application "Adobe Photoshop CS2"
   tell theDocument
      author of info
   end tell
end tell
--> "Ben Waldie"

Manipulating Images

Most Photoshop scripters will not simply want to access document properties and file information. Rather, they will want to get started with manipulating images. Photoshop's AppleScript dictionary contains numerous commands for performing various types of image manipulations. We'll explore a few of these now.

Resizing Image Documents

The resize command, which can be found in the Photoshop Suite of Photoshop's dictionary, may be used to change the height, width, and resolution of a document. This command is utilized in the following manner:

tell application "Adobe Photoshop CS2"
   tell theDocument
      resize image width 600 height 776 resolution 150 resample method bicubic
   end tell
end tell

Rotating Image Documents

To rotate the entire document, you may use the rotate canvas command, which is also found in the Photoshop Suite of Photoshop's dictionary. For this command, simply specify the angle that you want the document to be rotated. For example, the following code would rotate the document 90 degrees clockwise. You may specify a negative value to rotate counterclockwise.

tell application "Adobe Photoshop CS2"
   tell theDocument
      rotate canvas angle 90
   end tell
end tell

Alternatively, the rotate command may be used to rotate a specified layer, rather than the entire document.

Applying Filters

Another image manipulation that can be performed in Photoshop using AppleScript is the process of applying a filter to a document. This is done using the filter command, specifying a layer on which to apply the filter, and indicating the filter you wish to apply. For example:

tell application "Adobe Photoshop CS2"
   tell theDocument
      filter layer 1 using blur
   end tell
end tell

There are dozens of filters available, which can be applied to images via AppleScript. A list of scriptable filters can be found in the Filter Suite of Photoshop's dictionary. One thing to be aware of when scripting filter application, is that many filters require that you specify options for the filter, in order to apply it. The unsharp mask filter is a good example. In order to apply this filter, you must specify values for the filter's radius, amount, and threshold options.

To specify options for a filter when applying it, use the with options parameter with the filter command. For example:

tell application "Adobe Photoshop CS2"
   tell theDocument
      filter layer 1 using unsharp mask with options {amount:50, radius:1, threshold:0}
   end tell
end tell

When using filters, be aware that many filters will require that options be specified. To determine if a filter has required options, locate and view the class for the desired filter in Photoshop's dictionary.

Outputting Images

Now that we have discussed opening and manipulating images, let's talk briefly about outputting the images that our script may have just modified.

Saving Image Documents

In Photoshop, documents may be saved in a variety of formats, including EPS, GIF, JPEG, and TIFF, among others. To simply save a document in its current format, simply use the save command by itself, as follows.

tell application "Adobe Photoshop CS2"
   tell theDocument
      save
   end tell
end tell
--> document "My Document.eps" of application "Adobe Photoshop CS2"

To save a document into a new location, utilize the in parameter of the save command, and provide an output file path. When doing this, you will also want to specify the type of file that is saved. This is done via the as parameter of the save command.

tell application "Adobe Photoshop CS2"
   tell theDocument
      save in "Macintosh HD:Users:bwaldie:Desktop:My Document.jpg" as JPEG
   end tell
end tell
--> document "My Document.jpg" of application "Adobe Photoshop CS2"

The above example will save the document in JPEG format, using the default JPEG save options. When saving any type of file out of Photoshop, it is also possible to specify the save options that are used. The save options for each output file type can be found in the Save Formats Suite of Photoshop's dictionary. See figure 4.



Figure 4. Photoshop's Save Formats

To specify save options when saving an image, use the with options parameter of the save command. For example, the following sample code demonstrates how to save a document as a JPEG, using certain specified settings.

tell application "Adobe Photoshop CS2"
   tell theDocument
      save in "Macintosh HD:Users:bwaldie:Desktop:My Document.jpg" as JPEG with options 
      {class:JPEG save options, quality:12, format options:optimized}
   end tell
end tell
--> document "My Document.jpg" of application "Adobe Photoshop CS2"

Exporting Images for the Web

Another method of saving a document is to make use of Photoshop's Save For Web technology. Rather than using the save command, however, this process is done via the export command. In doing so, you may specify the Save for Web options to be used during the export. The complete set of Save For Web options can be found in the Export Formats Suite of Photoshop's dictionary. See figure 5.



Figure 5. Photoshop's Save For Web Export Options

The following example code will save an image in JPEG format via Photoshop's Save For Web technology, using specified export options. Due to a compilation issue with the as property of the save for web options class, in order to specify a file format when exporting in this format, a tricky workaround is necessary. Thanks to Nigel Garvey's insightful MacScripter.net AppleScript BBS <http://bbs.applescript.net> post for this great workaround!

tell application "Adobe Photoshop CS2"
   set theFormat to run script "tell application \"Photoshop\" to return {"class fltp":JPEG}"
   set theExportOptions to {class:save for web export options, interlaced:true, quality:30} & 
   theFormat
   tell theDocument
      export in "Macintosh HD:Users:bwaldie:Desktop:My_Document.jpg" as save for web with options 
      theExportOptions
   end tell
end tell

Resources for Continued Learning

If you are serious about getting started with scripting Photoshop, there are some resources that can help you to proceed. First, perhaps one of the most valuable resources available is the Photoshop scripting forum at the Adobe user-to-user forums. This forum, along with several other forums for scripting (and using) Adobe applications, can be found at <http://www.adobeforums.com/>.

Some other great resources for Photoshop scripters are the Photoshop CS2 AppleScript Reference Guide and the Photoshop CS2 Scripting Guide, both of which can be found on the Adobe website at <http://partners.adobe.com/public/developer/photoshop/sdk/index_scripting.html>. These documents will guide you through Photoshop's scripting support, and include example code and detailed information about Photoshop's AppleScript classes and commands.

In Closing

I hope that you now have a good idea of what is possible when it comes to scripting Photoshop. If you take some time to review Photoshop's dictionary in detail, you will find that there are plenty of other features that are accessible through scripting. If you use Photoshop in your daily routines, then you are more than likely encountering your fair share of time consuming and repetitive tasks. Sure, in some cases, you may be able to record a simple action to automate those processes. However, next time, I would encourage you to expand your horizons and try writing an AppleScript to do it instead.

Until next time, keep scripting!


Ben Waldie is the author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from <http://www.spiderworks.com>. Ben is also president of Automated Workflows, LLC, a company specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit <http://www.automatedworkflows.com>, or email Ben at <ben@automatedworkflows.com>.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.