Scripting Photoshop

Scripting Photoshop

For the first time, I needed to script the exporting of images from Photoshop documents. Normally, I would use my scriptable photo editing tool of choice for this: Acorn, but Acorn was unable to open these particular Photoshop documents and retain full fidelity.

So, I had to learn to script Photoshop.

My task is to convert a document containing an MRI image of the human brain and many layers highlighting structures within these MRI images into a series of PNG files.

Opening Documents

The first problem is that Photoshop’s open command does not return a reference to the opened document. The workaround is this:

set theDocument to choose file -- Get the Photoshop document to open
tell application "System Events"
	set theDocumentName to name of theDocument -- Get the document's name
	set theDocument to path of theDocument -- Photoshop does not accept the aliases returned by `choose file`, we need an HFS path
end tell

tell application "Adobe Photoshop CC 2019"
	--	Open the document if its not already open
	if not (exists document theDocumentName) then
		open file theDocument
	end if
	tell document theDocumentName
		-- commands directed at the opened document
		get name
	end tell
end tell

Manipulating Layers & Exporting

My task involved exporting individual layers from my Photoshop document. I accomplish this like this:

set exportFolder to "Users:mall:Desktop:Exported Images:" -- HFS path to the folder where the image should be written
set layersToShow to {"Background", "Lateral Fissure"}
tell application "Adobe Photoshop CC 2019"
	tell document theDocumentName
		--	Prepare the layers for export
		set visible of every layer to false -- turn off all layers
		set visible of layers whose name is in layersToShow to true -- turn on the layers I want
		
		--	Export the visible layers as a PNG file
		export as save for web in file (exportFolder & "Lateral Fissure.png") with options {class:save for web export options, web format:PNG}
	end tell
end tell

Closing Documents

And finally, when you are done with the document, you need to close it:

tell application "Adobe Photoshop CC 2019"
	tell document theDocumentName
		close saving no -- use `close saving yes` to save changes to your Photoshop document
	end tell
end tell

Just be aware that System Events actually returns lastPathComponent for the name property. So in the (unlikely) event of a / in a name, you’ll get back a : instead.

2 Likes

If you have window tabbing on the tabs get the file’s name.