Giter Club home page Giter Club logo

photoshop-scripting-python's Introduction

Photoshop Scripting in Python

Scripting in Photoshop is used to automate repetitive tasks and are often used as a creative tool to streamline tasks that might be too time consuming to do manually. For example, you could write a script to generate a number of localized versions of a particular image or to gather information about the various color profiles used by a collection of images.

Photoshop COM & DOM

Photoshop can be scripted through COM(Component Object Model). Its DOM(Document Object Model) is the same when accessing it through either its own JavaScript engine or Python or any other scripting language it supports. The Photoshop DOM consists of a hierarchical representation of the Photoshop application, the documents used in it, and the components of the documents. The DOM allows you to programmatically access and manipulate the document and its components. For example, through the DOM, you can create a new document, add a layer to an existing document, or change the background color of a layer. Most of the functionality available through the Photoshop user interface is available through the DOM.

But why Python?

Photoshop scripting officially supports JavaScript, AppleScript & VBScript. However, Scripting in Python is also fairly easy if not easier if you're already comfortable with Python. You may have already heard that Python is gaining in popularity, but did you know it’s now the most popular introductory programming language in U.S. universities? Python is also cross platform just like JavaScript is and lately becoming one of the fastest growing programming language according to StackOverflow as of 2017 / as of 2019

Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike. Python’s readability makes it a great first programming language - it allows you to think like a programmer and not waste time understanding the mysterious syntax that other programming languages can require.

Getting Started

Python allows you to access COM and it's DOM with the help of a Python extensions like "pypiwin32" or "comtypes". Install these modules and you're ready to start scripting Photoshop in Python

  • pip install pypiwin32 or pip install comtypes

Hello World!

from win32com.client import Dispatch

app = Dispatch("Photoshop.Application")
doc = app.Documents.Add(320, 240)
layerRef = doc.ArtLayers.Add()

psTextLayer = 2  # from enum PsLayerKind
layerRef.Kind = psTextLayer

textItem = layerRef.TextItem
textItem.Contents = "HELLO WORLD!"
textItem.Position = (120, 120)

How to inspect scripting object properties?

There's not a straight forward way, you need to read the documentation to understand what properties/attributes are available for a scripting object, or possibly a COM browser. For example, I've extracted the Python scripting object reference for Photoshop CC 2018 at api_reference

GUI tool example

See gui_tool for an example of how you can use Photoshop Scripting to develop your own tool/utilities

Scripting on Mac?

Yes, scripting on Mac is also possible, see mac_scripting for more details

Photoshop Scripting Resources

Also see

Contribution

If you've written a useful Photoshop Python script and wants to share with the world, please create a new issue with the file as an attachment to the issue.

When you submit a script, please try to include the following information at the start of your script

# script_file_name.py

# Created: 1st January 2019
__author__ = 'Your Name or Original Author Name'
__version__ = '1.0'

"""
A short description of what the script does
"""

"""
Instructions on how to use the script, if any
"""

photoshop-scripting-python's People

Contributors

lohriialo avatar oh-ok avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

photoshop-scripting-python's Issues

Cannot apply content aware filter to selected area.

Hello, I am trying to apply a content aware fill to a selected area in my currently opened Photoshop doc. However, when I try to run .putEnumerated with "contentAware" as an option, Python throws the following error:

    desc12.putEnumerated( idUsng, idFlCn, idcontentAware )
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py", 
line 516, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Adobe Photoshop', 'Illegal argument - argument 1\n- 
Required value is missing', None, 0, -2147220262), None) 

I am running this code with Python 3.7.6 on Windows Server 2019. I have successfully ran all the example code in this repo, but, again, the "contentAware" keyword seems to throw everything off. It is not clear what the "required value" is, per the error message, I have written the StringIDToTypeID and CharIDToTypeID the same as in the example code.
Full code is below:

# Get the active document and make a new selection.
import sys
from comtypes.client import GetActiveObject, CreateObject
from win32com.client import Dispatch

xPoint = int(sys.argv[2])
yPoint = int(sys.argv[3])
xWidth = int(sys.argv[4])
yWidth = int(sys.argv[5])
xSw = xPoint + xWidth
ySh = yPoint + yWidth
dialogMode = 3

# Make sure PS is OPEN here...

app = GetActiveObject("Photoshop.Application")
docRef = app.open(sys.argv[1])
# Make selection on document according to args
activeObj = app.ActiveDocument
sel_area = ((xPoint, yPoint), (xSw, yPoint), (xSw, ySh), (xPoint, ySh))
docRef.Selection.Select(sel_area, 1, 5.5, False) # Get rid of last three args 
idFl = app.CharIDToTypeID( "Fl  " )
desc12 = Dispatch('Photoshop.ActionDescriptor')
idUsng = app.CharIDToTypeID( "Usng" )
idFlCn = app.CharIDToTypeID( "FlCn" )
idcontentAware = app.StringIDToTypeID("contentAware")
desc12.putEnumerated( idUsng, idFlCn, idcontentAware )

How to use python to control Photoshop to automatically add jpg images to specified coordinates?

Thank you very much for sharing.
I am a developer of a startup company from China. I have been learning about your shared resources for almost 7 days. Thanks to your sharing, I have solved many problems, but because of my limited ability, I can only understand the sample code you wrote and will not write new functions. There are two problems that I have not solved yet. Please let me know.

1.How to use python to control Photoshop to automatically add jpg images to specified coordinates?
2.How to control Photoshop printing?

If you are convenient, you can email me a reply. [email protected]
We have seen the projects shared by programmers all over the world. Your sharing is the most valuable. If you need paid help, please come forward.
Thank you for your help.
jiahongtang

TypeError: 'Layers' object is not subscriptable

I cannot select a layer, this is my code

` import win32com.client as win32
import os
from comtypes.client import GetActiveObject, CreateObject

try:
adobe_app = win32.GetActiveObject("Photoshop.Application")
except:
adobe_app = win32.gencache.EnsureDispatch('Photoshop.Application')
try:
# cd = adobe_app.Open(filepath)
cd = adobe_app.ActiveDocument
except:
cd = adobe_app.ActiveDocument
# cd = adobe_app.ActiveDocument
currentTextLayer = cd.Layers[0]
print(currentTextLayer)

`

Any suggestions?

Whats the COM Object name, for Adobe After Effects Application ?

I'm working on a fork of your excellent library for Adobe After Effects full time.

Would you be so kind as to help me connect to the App object of Adobe After Effects ?

Based on your code, you connected to the Photoshop app object via:

from win32com.client import Dispatch

app = Dispatch("Photoshop.Application")

What would the equivalent Dispatch() be for Adobe After Effects ?

Thank you so much for your time,

Will happily pay for time spent on this,

All the best,
Sam

Mac Scripting guide suggestion

I’m trying to follow your mac scripting guide. https://github.com/lohriialo/photoshop-scripting-python/tree/master/mac_scripting

In usage:

from appscript import *

psApp = app('/Applications/Adobe Photoshop CC 2018/Adobe Photoshop CC 2018.app')
psApp.open(mactypes.Alias(file_name))

What file_name is referring to is unclear. It would be better if you change it to:

from appscript import *

file_name = '/path/to/your-psd-file.psd'
ps_app = app('/Applications/Adobe Photoshop CC 2018/Adobe Photoshop CC 2018.app')
ps_app.open(mactypes.Alias(file_name))

How to create an instance of BatchOptions?

There is an error: pywintypes.com_error: (-2147221164, 'Class not registered', None, None)
when I run this code:
from doc_reference.photoshop_CC_2018 import BatchOptions
batch_options = BatchOptions()

There is another error: pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Adobe Photoshop', 'Illegal argument - argument 4\n- Internal error', None, 0, -2147220259), None)
when I tried that:
app = Dispatch("Photoshop.Application")
batch_options = BatchOptions(app)
app.Batch(InputFiles=img_ref, Action=actions[5], From=action, Options=batch_options)

I need choose some options for the Batch command and I found these options in prop_map_get and prop_map_put, but I do not know how to do.

thank you

General Photoshop error occurred. This functionality may not be available in this version of Photoshop. The command "Play" is not currently available

I have person image with white background , and I have one more image which I am going to use it as new background for person. I am trying to do it in photoshop application with python script.

This is the script I have tried,

import os
import win32com.client

SILENT_CLOSE = 2

# This actually fires up Photoshop if not already running.
ps = win32com.client.Dispatch("Photoshop.Application")
ps.DisplayDialogs = 3            # psDisplayNoDialogs
ps.Preferences.RulerUnits = 1    # psPixels
folder_path = r"C:\Users\MCPL-265\Desktop\ps_connect\TEST\Input"

# Get a list of files in the folder
files = os.listdir(folder_path)
output_folder = r"C:\Users\MCPL-265\Desktop\ps_connect\TEST\Output"

# Create the output folder if it doesn't exist
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# Loop through the files and open them in Photoshop
for file in files:
    file_path = os.path.join(folder_path, file)
    ps.Open(file_path)

    ps.DoAction("Set1", "Actions")
    output_file = os.path.join(output_folder, file)

    jpgSaveOptions = win32com.client.Dispatch("Photoshop.JPEGSaveOptions" )
    ps.ActiveDocument.SaveAs(output_file, jpgSaveOptions, True, 2)

ps.Quit() # Stops the Photoshop application

NOTE : Here Set1 is the custom action that I have added already in photoshop application.
This is the custom action I have loaded.

But It is throwing this error

File "<COMObject Photoshop.Application>", line 2, in DoAction
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Adobe Photoshop', 'General Photoshop error occurred. This functionality may not be available in this version of Photoshop.\n- The command "Play" is not currently available.', None, 0, -2147212704), None)

Please can anyone help me to resolve this issue?

MemoryError: CreatingSafeArray

app = Dispatch("Photoshop.Application")
img_ref = (
'C:\Users\Owlii\Desktop\psdemo\jingkong\1.png',
'C:\Users\Owlii\Desktop\psdemo\jingkong\2.png',
'C:\Users\Owlii\Desktop\psdemo\jingkong\3.png')

actions = [ 'Action 1', 'Action 2']

app.Batch(InputFiles=img_ref, Action=actions[0], From=actions)

thanks for your time!

layer.typename is not found?

There is an error: NameError: Name typename not found when I run this code:

from comtypes.client import GetActiveObject
app = GetActiveObject("Photoshop.Application")
srcDoc = app.Open("E:\\Project\\Page_To_Bar\\images\\MangaTest.psd")
print("type", app.activeDocument.activeLayer.typename)

I sure layer.typename is aviliable in ADOBE PHOTOSHOP CC 2015 JAVASCRIPT SCRIPTING REFERENCE
Can you help me?
Thank you.

Example of setting/getting the active tool?

Thank you so much for these awesome examples, your repo is the best source of info I have found on using python with Adobe ps. I've been trying to get and set the active Photoshop tool via python and I just don't think I have the syntax quite right because all the examples are in JavaScript. Does anyone happen to have an example of doing this in Python?

How to adjust HDR Toning

I want to adjust HDR Toning
But I don't know how to use it



// =======================================================
var idOpn = charIDToTypeID( "Opn " );
    var desc225 = new ActionDescriptor();
    var iddontRecord = stringIDToTypeID( "dontRecord" );
    desc225.putBoolean( iddontRecord, false );
    var idforceNotify = stringIDToTypeID( "forceNotify" );
    desc225.putBoolean( idforceNotify, true );
    var idnull = charIDToTypeID( "null" );
    desc225.putPath( idnull, new File( "E:\\2023_ShuJu\\X\\group1\\1.tiff" ) );
    var idDocI = charIDToTypeID( "DocI" );
    desc225.putInteger( idDocI, 59 );
    var idtemplate = stringIDToTypeID( "template" );
    desc225.putBoolean( idtemplate, false );
executeAction( idOpn, desc225, DialogModes.NO );

// =======================================================
var idAdobeScriptAutomationScripts = stringIDToTypeID( "AdobeScriptAutomation Scripts" );
    var desc309 = new ActionDescriptor();
    var idjsCt = charIDToTypeID( "jsCt" );
    desc309.putPath( idjsCt, new File( "C:\\Program Files\\Adobe\\Adobe Photoshop 2023\\Required\\HDRToning.jsx" ) );
    var idjsMs = charIDToTypeID( "jsMs" );
    desc309.putString( idjsMs, """undefined""" );
executeAction( idAdobeScriptAutomationScripts, desc309, DialogModes.NO );


chavez_fig02

Photoshop is not opening with Dispatch

Traceback (most recent call last):
File "D:\PyCharm\Adobe\venv\lib\site-packages\win32com\client\dynamic.py", line 84, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\PyCharm\Adobe\main.py", line 3, in
app = Dispatch("Photoshop.Application")
File "D:\PyCharm\Adobe\venv\lib\site-packages\win32com\client_init_.py", line 118, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
File "D:\PyCharm\Adobe\venv\lib\site-packages\win32com\client\dynamic.py", line 104, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "D:\PyCharm\Adobe\venv\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)

Import datasets

Hi,
Is it possible to import datasets with a script ?
Image > Variables > Data Sets
Thank you

Is there a macOS equivalent?

This project seems Windows-specific. Do you know if there is a macOS equivalent method for this API access? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.