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

LaunchBar 6.18.5 - Powerful file/URL/ema...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Affinity Designer 2.3.0 - Vector graphic...
Affinity Designer is an incredibly accurate vector illustrator that feels fast and at home in the hands of creative professionals. It intuitively combines rock solid and crisp vector art with... Read more
Affinity Photo 2.3.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
WhatsApp 23.24.78 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Adobe Photoshop 25.2 - Professional imag...
You can download Adobe Photoshop as a part of Creative Cloud for only $54.99/month Adobe Photoshop is a recognized classic of photo-enhancing software. It offers a broad spectrum of tools that can... Read more
PDFKey Pro 4.5.1 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Skype 8.109.0.209 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
OnyX 4.5.3 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
CrossOver 23.7.0 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more
Tower 10.2.1 - Version control with Git...
Tower is a Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power of Git.... Read more

Latest Forum Discussions

See All

Pour One Out for Black Friday – The Touc...
After taking Thanksgiving week off we’re back with another action-packed episode of The TouchArcade Show! Well, maybe not quite action-packed, but certainly discussion-packed! The topics might sound familiar to you: The new Steam Deck OLED, the... | Read more »
TouchArcade Game of the Week: ‘Hitman: B...
Nowadays, with where I’m at in my life with a family and plenty of responsibilities outside of gaming, I kind of appreciate the smaller-scale mobile games a bit more since more of my “serious" gaming is now done on a Steam Deck or Nintendo Switch.... | Read more »
SwitchArcade Round-Up: ‘Batman: Arkham T...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 1st, 2023. We’ve got a lot of big games hitting today, new DLC For Samba de Amigo, and this is probably going to be the last day this year with so many heavy hitters. I... | Read more »
Steam Deck Weekly: Tales of Arise Beyond...
Last week, there was a ton of Steam Deck coverage over here focused on the Steam Deck OLED. | Read more »
World of Tanks Blitz adds celebrity amba...
Wargaming is celebrating the season within World of Tanks Blitz with a new celebrity ambassador joining this year's Holiday Ops. In particular, British footballer and movie star Vinnie Jones will be brightening up the game with plenty of themed in-... | Read more »
KartRider Drift secures collaboration wi...
Nexon and Nitro Studios have kicked off the fifth Season of their platform racer, KartRider Dift, in quite a big way. As well as a bevvy of new tracks to take your skills to, and the new racing pass with its rewards, KartRider has also teamed up... | Read more »
‘SaGa Emerald Beyond’ From Square Enix G...
One of my most-anticipated releases of 2024 is Square Enix’s brand-new SaGa game which was announced during a Nintendo Direct. SaGa Emerald Beyond will launch next year for iOS, Android, Switch, Steam, PS5, and PS4 featuring 17 worlds that can be... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
This week, there is no new release for Apple Arcade, but many notable games have gotten updates ahead of next week’s holiday set of games. If you haven’t followed it, we are getting a brand-new 3D Sonic game exclusive to Apple Arcade on December... | Read more »
New ‘Honkai Star Rail’ Version 1.5 Phase...
The major Honkai Star Rail’s 1.5 update “The Crepuscule Zone" recently released on all platforms bringing in the Fyxestroll Garden new location in the Xianzhou Luofu which features many paranormal cases, players forming a ghost-hunting squad,... | Read more »
SwitchArcade Round-Up: ‘Arcadian Atlas’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 30th, 2023. It’s Thursday, and unlike last Thursday this is a regular-sized big-pants release day. If you like video games, and I have to believe you do, you’ll want to... | Read more »

Price Scanner via MacPrices.net

Deal Alert! Apple Smart Folio Keyboard for iP...
Apple iPad Smart Keyboard Folio prices are on Holiday sale for only $79 at Amazon, or 50% off MSRP: – iPad Smart Folio Keyboard for iPad (7th-9th gen)/iPad Air (3rd gen): $79 $79 (50%) off MSRP This... Read more
Apple Watch Series 9 models are now on Holida...
Walmart has Apple Watch Series 9 models now on Holiday sale for $70 off MSRP on their online store. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
Holiday sale this weekend at Xfinity Mobile:...
Switch to Xfinity Mobile (Mobile Virtual Network Operator..using Verizon’s network) and save $500 instantly on any iPhone 15, 14, or 13 and up to $800 off with eligible trade-in. The total is applied... Read more
13-inch M2 MacBook Airs with 512GB of storage...
Best Buy has the 13″ M2 MacBook Air with 512GB of storage on Holiday sale this weekend for $220 off MSRP on their online store. Sale price is $1179. Price valid for online orders only, in-store price... Read more
B&H Photo has Apple’s 14-inch M3/M3 Pro/M...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on Holiday sale this weekend for $100-$200 off MSRP, starting at only $1499. B&H offers free 1-2 day delivery to most... Read more
15-inch M2 MacBook Airs are $200 off MSRP on...
Best Buy has Apple 15″ MacBook Airs with M2 CPUs in stock and on Holiday sale for $200 off MSRP on their online store. Their prices are among the lowest currently available for new 15″ M2 MacBook... Read more
Get a 9th-generation Apple iPad for only $249...
Walmart has Apple’s 9th generation 10.2″ iPads on sale for $80 off MSRP on their online store as part of their Cyber Week Holiday sale, only $249. Their prices are the lowest new prices available for... Read more
Space Gray Apple AirPods Max headphones are o...
Amazon has Apple AirPods Max headphones in stock and on Holiday sale for $100 off MSRP. The sale price is valid for Space Gray at the time of this post. Shipping is free: – AirPods Max (Space Gray... Read more
Apple AirTags 4-Pack back on Holiday sale for...
Amazon has Apple AirTags 4 Pack back on Holiday sale for $79.99 including free shipping. That’s 19% ($20) off Apple’s MSRP. Their price is the lowest available for 4 Pack AirTags from any of the... Read more
New Holiday promo at Verizon: Buy one set of...
Looking for more than one set of Apple AirPods this Holiday shopping season? Verizon has a great deal for you. From today through December 31st, buy one set of AirPods on Verizon’s online store, and... Read more

Jobs Board

Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and offer a Read more
Senior Manager, Product Management - *Apple*...
…Responsibilities** We are seeking an ambitious, data-driven thinker to assist the Apple Product Development team as our Wireless Product division continues to grow Read more
Mobile Platform Engineer ( *Apple* /AirWatch)...
…systems, installing and maintaining certificates, navigating multiple network segments and Apple /IOS devices, Mobile Device Management systems such as AirWatch, and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.