Search
Filters

Access Photoshop API via Powershell script

Access Photoshop API via Powershell script

Access Photoshop API with Powershell

Powershell has been on everyone's lips for years, but even the current Adobe SDK for Photoshop 2019 deals only with examples of JavaScript, VbScript and AppleScript. Since 2006 Powershell has been favored by Microsft as a scripting language and made palatable to administrators and programmers with a lot of passion - but Adobe is unfortunately slightly hard of hearing on this ear.

If you look at the Adobe Photoshop SDK, the implementation is of course possible with the appropriate background knowledge. But especially for newcomers or VbScript users it is difficult.

If you go on an example hunt via the search engines, you will quickly notice that Powershell is actually the script language. Especially since Powershell 6.0 exists and this language is not only used on Windows, but also on Linux and Apple systems. So it's all the more surprising that there are virtually no examples of this.

What could be more obvious than using Powershell to control Photoshop? We tried it and it just works fanatically. Due to the many modern possibilities fantastic scenarios can be automated.

In this blog we have put together a working library with which even beginners can adapt a process to their own needs. If you are looking for something ready to use, you will find a ready solution at the end, which we offer via our website.

We have packed the starting and closing of Photoshop into two functions, which everyone can adapt very easily for himself.

 

 

The Functions

 

Deregistering COM Objects

The function "Unregister.ComObject" removes the instances of Photoshop. This function is useful for releasing any Com objects.

Function Unregister-ComObject($Reference, $ObjectName) {
try {
if ($Reference) {
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Reference) | out-null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Start-Sleep -Milliseconds 500
$Reference = $null
} else { Write-Host "WARNING! Object '$Objectname' was not instantiated before.! $_" -foregroundcolor "magenta" }
} catch {
Write-Host "ERROR! Exception occured, releasing object '$Objectname' failed! $_" -foregroundcolor "red"
}
}

The Set-CloseWindow function closes Windows applications that are accessible via a window title. This requires a Windows API which is embedded in the Powershell function.

 

Close Windows application

$WinApi = @"
using System;
using System.Runtime.InteropServices;
public class WinApi {
[DllImport("user32.dll")]
public static extern int PostMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
}
"@
Add-Type $WinApi

function Set-CloseWindow($proc) {
try {
$p = Get-Process | Where-Object {$_.mainWindowTItle } | Where-Object {$_.Name -like "$proc"}
if ($p) {
$h = $p.MainWindowHandle
if ($h) {
[void] [WinApi]::PostMessage($h, 0x10, 0, 0)
} else { Write-Host "WARNING: No valid handle found for '$Proc'" -foregroundcolor "magenta" }
} else { Write-Host "WARNING: No process found for '$Proc'" -foregroundcolor "magenta" }
} catch {
Write-Host "ERROR: Exception occured, the application '$Proc' could not be closed. $_" -foregroundcolor "red"
}
}

 

Open-Photoshop starts Photoshop, if the program was started before, this instance will be used automatically. In addition, the export object is instantiated. The export function is optimized for creating web-optimized images.

 

Start and stop Photoshop

Function Open-Photoshop() {
[int] $PsPixels = 1
[int] $PsDisplayNoDialogs = 3

try {
$Script:PsObj = New-Object -ComObject "Photoshop.Application.130"
$Script:ExportObj = New-Object -ComObject "Photoshop.ExportOptionsSaveForWeb.130"

# Save Defaults
$Script:OldRulerUnits = $Script:PsObj.Preferences.RulerUnits
$Script:OldTypeUnits = $Script:PsObj.Preferences.TypeUnits
$Script:OldDisplayDialogs = $Script:PsObj.DisplayDialogs

# Set our Defaults
$Script:PsObj.Preferences.RulerUnits = $PsPixels
$Script:PsObj.Preferences.TypeUnits = $PsPixels
$Script:PsObj.DisplayDialogs = $PsDisplayNoDialogs
Return $True
} catch {
Write-Host "ERROR: Exception occured creating photoshop.application object. $_" -foregroundcolor "red"
Return $false
}
}

At the end of the export, the ComObjects are released again and a CloseWindow message is sent to the window - Photoshop is closed.

Function Close-Photoshop() {
# Restore Defaults
if ($Script:PsObj) {
$Script:PsObj.Preferences.RulerUnits = $Script:OldRulerUnits
$Script:PsObj.Preferences.TypeUnits = $Script:OldTypeUnits
$Script:PsObj.DisplayDialogs = $Script:OldDisplayDialogs
}

Unregister-ComObject $Script:ExportObj "Photoshop.ExportOptionsSaveForWeb"
Unregister-ComObject $Script:PsObj "Photoshop.Application"
Set-CloseWindow "photoshop"
}


Export image in PSD format to PNG

The core function exports the loaded image to the PNG format. 


Function Export-Png([string] $FilePath) {
try {
[int] $PsSavePNG = 13
[int] $PsExportSAVEFORWEB = 2
[int] $PsDoNotSaveChanges = 2

$Doc = $Script:PsObj.Open($FilePath)
$Script:ExportObj.format = $PsSavePNG
$Script:ExportObj.PNG8 = $True
$Script:ExportObj.Transparency = $True
$Script:ExportObj.Interlaced = $True
$Script:ExportObj.Quality = 8
$FName = [io.path]::ChangeExtension($FilePath, "png")
$Doc.Export($FName,$PsExportSAVEFORWEB, $Script:ExportObj)
$Script:PsObj.ActiveDocument.Close($PsDoNotSaveChanges)
} catch {
Write-Host "ERROR: Exception occured on exporting png for the web. $_" -foregroundcolor "red"
Return $false
}
Return $true
}

 

 

Main routine

The simplified main program converts the file "test.psd" from the desktop to the png format.

if (Open-Photoshop) {
$DesktopPath = [Environment]::GetFolderPath("Desktop")
Export-Png "$DesktopPath\test.psd" | Out-Null
Close-Photoshop
}

 

These few functions allow you to load a Photoshop file in PSD format and export it as PNG optimized for the web. The description of the SDK can be found on the Adobe website at https://www.adobe.com/devnet/photoshop/scripting.html and can quickly turn this simple example into a complex application.

 

 

Download

The example script described here can be downloaded free of charge via Github. GitHub: Eulanda/PsPhotoshopApi

 

 

More complex export script

We did this and created a nearly 1000 line Powershell script. It searches a directory for psd files - recursively with subfolders if desired - and exports the image as png or jpg file. Further parameters influence the image quality, transparency of png images or interlaced. The last one allows to display an image while loading.

Every psd file is provided with a check number, so that only modified psd files are converted again when the script is called several times. By deleting the checksum file you can of course export all images again at any time.

The script also supports the -verbose parameter with extended screen output and the "-whatif" parameter which simulates an export and shows at the end how many psd-files are identical, changed, new or deleted from the disk in the meantime.

The target directory can also be a cloud drive like Onedrive. Before the image is loaded, a routine tests whether the image file is writable and therefore not in synchronization at this moment. The waiting time, i.e. the timeout until the program continues with the next image can be set in the script.

The script PsPsdConvert.ps1 can be called several times a day and converts the PSD files that have not been converted before. This solution is suitable, for example, to integrate a shop interface into the workflow of the graphics department.

Price: 49.- EUR inkl. VAT

To the final product: PSD Convert

Leave your comment