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

Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more

Jobs Board

IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.