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>.

 
AAPL
$102.64
Apple Inc.
+1.58
MSFT
$46.56
Microsoft Corpora
-0.50
GOOG
$581.13
Google Inc.
-6.24

MacTech Search:
Community Search:

Software Updates via MacUpdate

GarageSale 6.8 - Create outstanding eBay...
GarageSale is a slick, full-featured client application for the eBay online auction system. Create and manage your auctions with ease. With GarageSale, you can create, edit, track, and manage... Read more
ScreenFlow 4.5.3 - Create screen recordi...
Save 5% with the MacUpdate coupon code: 68031AE15F -- Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your entire... Read more
NeoOffice 2014.3 - Mac-tailored, OpenOff...
NeoOffice is a complete office suite for OS X. With NeoOffice, users can view, edit, and save OpenOffice documents, PDF files, and most Microsoft Word, Excel, and PowerPoint documents. NeoOffice 3.x... Read more
Typinator 6.2 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
PopChar X 6.7 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
Evernote 5.6.0 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
Monosnap 2.2.2 - Versatile screenshot ut...
Monosnap allows you to save screenshots easily, conveniently, and quickly, sharing them with friends and colleagues at once. It's the ideal choice for anyone who is looking for a smart and fast... Read more
Tunnelblick 3.4beta36 - GUI for OpenVPN...
Tunnelblick is a free, open source graphic user interface for OpenVPN on OS X. It provides easy control of OpenVPN client and/or server connections. It comes as a ready-to-use application with all... Read more
SoftRAID 5.0.4 - High-quality RAID manag...
SoftRAID allows you to create and manage disk arrays to increase performance and reliability. SoftRAID's intuitive interface and powerful feature set makes this utility a must have for any Mac OS X... Read more
Audio Hijack Pro 2.11.3 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more

Latest Forum Discussions

See All

Why I Don’t Want to Upgrade to the iPhon...
I’ve been living with my iPhone 4S for the past two years or so, and if I was living in a world where I wasn’t bombarded with new phone announcements and people of the general public caring enough to upgrade constantly, I wouldn’t think my phone... | Read more »
Tictail Review
Tictail Review By Jennifer Allen on September 23rd, 2014 Our Rating: :: CLASSY SHOPPINGiPhone App - Designed for the iPhone, compatible with the iPad Tictail is an attractive and stylish way of looking for some great new clothes... | Read more »
Super Glyph Quest is Bringing More Match...
Super Glyph Quest is Bringing More Match-3 Magics to the App Store Soon Posted by Jessica Fisher on September 23rd, 2014 [ permalink ] Fans of Glyph Quest, by Alex Trowers and Leanne Bayley, | Read more »
Sword King Review
Sword King Review By Jennifer Allen on September 23rd, 2014 Our Rating: :: WEAK, SO WEAKUniversal App - Designed for iPhone and iPad Ever wanted to tap on a screen and assume you’ve killed a monster or two? Probably not, but just... | Read more »
Pangea Software Unveil Bundles and iOS 8...
Pangea Software Unveil Bundles and iOS 8 Updates Posted by Ellis Spice on September 23rd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Race Team Manager Review
Race Team Manager Review By Jennifer Allen on September 23rd, 2014 Our Rating: :: LIGHT RACINGUniversal App - Designed for iPhone and iPad Want to be in charge of a racing team but not be overwhelmed by tactics and options? Race... | Read more »
Kobojo Works with Creative Minds from Fi...
Kobojo has announced details for their newest game, Zodiac – a 2D persistent online RPG. Kobojo has put together a crack team of developers including composer Hitoshi Sakimoto and scenario writer Kazushige Nojima, whose work includes many of the... | Read more »
PlayHaus Review
PlayHaus Review By Amy Solomon on September 23rd, 2014 Our Rating: iPad Only App - Designed for the iPad PlayHaus is a interesting, stylish app for young children, full of cause-and-effect interactions.   | Read more »
Astropolo Review
Astropolo Review By Amy Solomon on September 23rd, 2014 Our Rating: Universal App - Designed for iPhone and iPad Astropolo is a space-themed children’s app with a great sense of style.   | Read more »
New E*TRADE Update Includes Touch ID and...
New E*TRADE Update Includes Touch ID and Home Screen Widget for iOS 8 Posted by Jessica Fisher on September 23rd, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Razer DeathAdder Chroma Gaming Mouse Upgraded...
Razer has announced the launch of their new Razer DeathAdder Chroma gaming mouse. Even if you’re not a gamer, the DeathAdder bears considering. I’m a fan of the hard-wired tracking accuracy,... Read more
Check Apple prices on your device with iTracx
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
Refurbished 2013 MacBook Pros available for u...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available starting at $929. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros (4GB RAM/... Read more
New iPhones Score Big in SquareTrade Breakabi...
SquareTrade has announced the iPhone 6 and its larger sibling, iPhone 6 Plus, performed impressively in Breakability testing, and each carries the top Breakability Score in their respective category... Read more
10 Million + First Weekend Sales Set New iPho...
Apple has announced it sold over 10 million new iPhone 6 and iPhone 6 Plus models, a new record, just three days after the launch on September 19. iPhone 6 and iPhone 6 Plus are now available in the... Read more
Betty Crocker Launches New Cookbook for iOS
Betty Crocker, a General Mills brand, an established food industry leader, has announced its free digital cookbook app has been refreshed to make cooking with iPhone, iPad and iPod touch even easier... Read more
Apple restocks some refurbished 2014 MacBook...
The Apple Store has restocked some Apple Certified Refurbished 2014 MacBook Airs, with prices starting at $769. An Apple one-year warranty is included with each MacBook, and shipping is free. These... Read more
13-inch 128GB MacBook Air on sale for $949, s...
B&H Photo has the new 2014 13″ 1.4GHz/128GB MacBook Air on sale for $949.99 including free shipping plus NY tax only. Their price is $50 off MSRP. B&H will also include free copies of... Read more
Apple offering free $25 iTunes Gift Card with...
The Apple Store is offering a free $25 iTunes Gift Card with the purchase of a $99 Apple TV for a limited time. Shipping is free. Read more
Apple refurbished iPod touch available for up...
The Apple Store has Apple Certified Refurbished 5th generation iPod touches available starting at $149. Apple’s one-year warranty is included with each model, and shipping is free. Most colors are... Read more

Jobs Board

Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.