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

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... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.