Examples
Operate Layer Set
"""Example of working with layer sets (groups) in Photoshop. This example demonstrates how to: 1. Create and manage layer groups 2. Add layers to groups 3. Organize layer hierarchy 4. Handle group properties Key concepts: - Layer groups - Layer organization - Group properties - Layer hierarchy """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create a new layer group main_group = doc.layerSets.add() main_group.name = "Main Group" # Create a nested group sub_group = main_group.layerSets.add() sub_group.name = "Sub Group" # Add layers to groups layer1 = main_group.artLayers.add() layer1.name = "Layer in Main" layer2 = sub_group.artLayers.add() layer2.name = "Layer in Sub" # Set group properties main_group.visible = True main_group.opacity = 80 # List layers in groups for layer in main_group.layers: ps.echo(f"Layer in main group: {layer.name}") for layer in sub_group.layers: ps.echo(f"Layer in sub group: {layer.name}") # Move a layer between groups layer1.move(sub_group, ps.ElementPlacement.INSIDE) Hello World
"""Basic example demonstrating Photoshop automation with python-photoshop-api. This example demonstrates how to: 1. Connect to Photoshop application 2. Create a new document 3. Add text content to the document 4. Save the document as PSD file Key concepts: - Application connection - Document creation - Text layer manipulation - File saving """ # Import built-in modules import os # Import local modules from photoshop import Session with Session() as ps: # Create a new document doc = ps.app.documents.add() # Create text layer with "Hello, World!" text_color = ps.SolidColor() text_color.rgb.red = 255 text_color.rgb.green = 0 text_color.rgb.blue = 0 new_text_layer = doc.artLayers.add() new_text_layer.kind = ps.LayerKind.TextLayer new_text_layer.textItem.contents = "Hello, World!" new_text_layer.textItem.position = [160, 167] new_text_layer.textItem.size = 40 new_text_layer.textItem.color = text_color # Save the document jpg_file = os.path.join(os.path.dirname(__file__), "hello_world.jpg") ps.JPEGSaveOptions(quality=12) doc.saveAs(jpg_file) Session Smart Sharpen
"""This script demonstrates how you can use the action manager to execute the Emboss filter. References: https://github.com/lohriialo/photoshop-scripting-python/blob/master/SmartSharpen.py """ # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() file_path = PSD_FILE["layer_comps.psd"] with Session(file_path, action="open") as ps: def SmartSharpen(inAmount, inRadius, inNoise): idsmart_sharpen_id = ps.app.stringIDToTypeID(ps.EventID.SmartSharpen) desc37 = ps.ActionDescriptor() idpresetKind = ps.app.stringIDToTypeID(ps.EventID.PresetKind) idpresetKindType = ps.app.stringIDToTypeID(ps.EventID.PresetKindType) idpresetKindCustom = ps.app.stringIDToTypeID(ps.EventID.PresetKindCustom) desc37.putEnumerated(idpresetKind, idpresetKindType, idpresetKindCustom) idAmnt = ps.app.charIDToTypeID("Amnt") idPrc = ps.app.charIDToTypeID("Rds ") desc37.putUnitDouble(idAmnt, idPrc, inAmount) idRds = ps.app.charIDToTypeID("Rds ") idPxl = ps.app.charIDToTypeID("#Pxl") desc37.putUnitDouble(idRds, idPxl, inRadius) idnoiseReduction = ps.app.stringIDToTypeID("noiseReduction") idPrc = ps.app.charIDToTypeID("#Prc") desc37.putUnitDouble(idnoiseReduction, idPrc, inNoise) idblur = ps.app.charIDToTypeID("blur") idblurType = ps.app.stringIDToTypeID("blurType") idGsnB = ps.app.charIDToTypeID("GsnB") desc37.putEnumerated(idblur, idblurType, idGsnB) ps.app.ExecuteAction(idsmart_sharpen_id, desc37) docRef = ps.active_document nlayerSets = docRef.layerSets nArtLayers = docRef.layerSets.item(nlayerSets.length) docRef.activeLayer = nArtLayers.artLayers.item(nArtLayers.artLayers.length) SmartSharpen(300, 2.0, 20) Move To End
"""Example of moving layers to different positions in the layer stack. This example demonstrates how to: 1. Move layers within the layer stack 2. Change layer order 3. Handle layer positioning 4. Work with layer groups Key concepts: - Layer ordering - Layer movement - Stack manipulation - Layer hierarchy """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create some test layers layer1 = doc.artLayers.add() layer1.name = "Layer 1" layer2 = doc.artLayers.add() layer2.name = "Layer 2" layer3 = doc.artLayers.add() layer3.name = "Layer 3" # Move layer1 to the end (bottom) of the stack layer1.move(doc.layers[-1], ps.ElementPlacement.PlaceAfter) # Move layer3 to the beginning (top) of the stack layer3.move(doc.layers[0], ps.ElementPlacement.PlaceBefore) # Move layer2 between layer1 and layer3 layer2.move(layer1, ps.ElementPlacement.PlaceBefore) Active Layer
"""Example of working with active layers in Photoshop. This example demonstrates how to: 1. Get and set the active layer in a document 2. Create new art layers 3. Manage layer names and properties The script will: - Create a new document if none exists - Add a new art layer if document has less than 2 layers - Display the current active layer name - Create a new layer and rename it """ # Import local modules from photoshop import Session with Session() as ps: # Get or create a document if len(ps.app.documents) < 1: docRef = ps.app.documents.add() else: docRef = ps.app.activeDocument # Ensure we have at least 2 layers if len(docRef.layers) < 2: docRef.artLayers.add() # Display current active layer name ps.echo(docRef.activeLayer.name) # Create and rename a new layer new_layer = docRef.artLayers.add() ps.echo(new_layer.name) new_layer.name = "test" Get Layer By Name
"""Example of retrieving a layer by its name in Photoshop. This example demonstrates how to: 1. Access layers in the active document 2. Find a specific layer by its name 3. Handle layer search in the document hierarchy Key concepts: - Layer navigation - Name-based layer lookup - Active document context """ # Import local modules from photoshop import Session with Session() as ps: # Access active document's layers doc = ps.app.activeDocument for layer in doc.layers: if layer.name == "example layer": ps.echo(layer.name) break Import Image As Layer
"""Import a image as a artLayer.""" # Import local modules from photoshop import Session with Session(action="new_document") as ps: desc = ps.ActionDescriptor desc.putPath(ps.app.charIDToTypeID("null"), "your/image/path") event_id = ps.app.charIDToTypeID("Plc ") # `Plc` need one space in here. ps.app.executeAction(ps.app.charIDToTypeID("Plc "), desc) Replace Images
"""Replace the image of the current active layer with a new image.""" # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() with Session(PSD_FILE["replace_images.psd"], action="open") as ps: active_layer = ps.active_document.activeLayer bounds = active_layer.bounds print(f"current layer {active_layer.name}: {bounds}") input_file = PSD_FILE["red_100x200.png"] replace_contents = ps.app.stringIDToTypeID("placedLayerReplaceContents") desc = ps.ActionDescriptor idnull = ps.app.charIDToTypeID("null") desc.putPath(idnull, input_file) ps.app.executeAction(replace_contents, desc) # replaced image. active_layer = ps.active_document.activeLayer current_bounds = active_layer.bounds width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] current_width = current_bounds[2] - current_bounds[0] current_height = current_bounds[3] - current_bounds[1] new_size = width / current_width * 100 active_layer.resize(new_size, new_size, ps.AnchorPosition.MiddleCenter) print(f"current layer {active_layer.name}: {current_bounds}") Session Document Duplicate
"""Example of duplicating documents within a Photoshop session. This example demonstrates how to: 1. Duplicate existing documents 2. Configure duplication options 3. Handle document copies 4. Manage document references Key concepts: - Document duplication - Session management - Document handling - Copy options """ # Import local modules from photoshop import Session with Session() as ps: if len(ps.app.documents) > 0: # Duplicate active document doc = ps.active_document.duplicate() Fit On Screen
"""Let the current document Fit on screen.""" # Import local modules from photoshop import Session with Session() as ps: ps.app.runMenuItem(ps.app.charIDToTypeID("FtOn")) List Documents
"""List current photoshop all documents.""" # Import local modules import photoshop.api as ps app = ps.Application() doc = app.documents[0] print(doc.name) for doc in app.documents: print(doc.name) Export Document With Options
"""This example demonstrates how to export a document with different formats. References: https://github.com/loonghao/photoshop-python-api/issues/368 """ # Import built-in modules import os # Import third-party modules from photoshop import Session from photoshop.api.enumerations import DitherType from photoshop.api.enumerations import ExportType from photoshop.api.enumerations import SaveDocumentType from photoshop.api.save_options.png import PNGSaveOptions from photoshop.api.save_options.jpg import JPEGSaveOptions from photoshop.api.save_options.png import ExportOptionsSaveForWeb def main(): """Export document with different formats.""" psd_file = os.path.join(os.path.dirname(__file__), "files", "export_layers_as_png.psd") if not os.path.exists(psd_file): raise FileNotFoundError( f"File not found: {psd_file}" ) # Start a new photoshop session with Session(psd_file, "open") as ps: doc = ps.active_document # Export as PNG-24 png_path = os.path.join(os.path.dirname(__file__), "exported_png24.png") png_options = PNGSaveOptions() png_options.interlaced = False # Disable interlacing for better quality png_options.compression = 0 # Set compression to 0 for maximum quality doc.saveAs(png_path, png_options, True) # True for saving as copy print(f"Exported PNG-24: {png_path}") # Export as JPEG with high quality jpg_path = os.path.join(os.path.dirname(__file__), "exported_jpeg.jpg") jpg_options = JPEGSaveOptions() jpg_options.quality = 12 # Set quality to maximum (12) jpg_options.embedColorProfile = True # Preserve color profile jpg_options.formatOptions = 1 # Use standard baseline format jpg_options.scans = 3 # Enable progressive scanning jpg_options.matte = 1 # No background color (matte) doc.saveAs(jpg_path, jpg_options, True) # True for saving as copy print(f"Exported JPEG: {jpg_path}") # Export as GIF using Save for Web gif_path = os.path.join(os.path.dirname(__file__), "exported_gif.gif") gif_options = ExportOptionsSaveForWeb() gif_options.format = SaveDocumentType.CompuServeGIFSave # Set format to GIF gif_options.colors = 256 # Use maximum number of colors (256) gif_options.dither = DitherType.NoDither # Disable dithering for sharper edges gif_options.transparency = True # Preserve transparency in the GIF doc.exportDocument(gif_path, ExportType.SaveForWeb, gif_options) print(f"Exported GIF: {gif_path}") if __name__ == "__main__": main() Copy And Paste
""" References: https://github.com/lohriialo/photoshop-scripting-python/blob/master/CopyAndPaste.py """ # Import local modules import photoshop.api as ps app = ps.Application() startRulerUnits = app.preferences.rulerUnits app.preferences.rulerUnits = ps.Units.Inches doc = app.documents.add(7, 5, 72, None, ps.NewDocumentMode.NewRGB, ps.DocumentFill.White) # Make sure the active layer is not a text layer, which cannot be copied to the # clipboard. if doc.activeLayer.kind != ps.LayerKind.TextLayer: # Select the left half of the document. Selections are always expressed # in pixels regardless of the current ruler unit type, so we're computing # the selection corner points based on the inch unit width and height # of the document x2 = (doc.width * doc.resolution) / 2 y2 = doc.height * doc.resolution sel_area = ((0, 0), (x2, 0), (x2, y2), (0, y2)) doc.selection.select(sel_area, ps.SelectionType.ReplaceSelection, 0, False) doc.selection.copy() # The new doc is created # need to change ruler units to pixels because x2 and y2 are pixel units. app.preferences.rulerUnits = ps.Units.Pixels pasteDoc = app.documents.add(x2, y2, doc.resolution, "Paste Target") pasteDoc.paste() else: print("You cannot copy from a text layer") if startRulerUnits != app.preferences.rulerUnits: app.preferences.rulerUnits = startRulerUnits Add Metadata
"""Add metadata to current active document.""" # Import built-in modules import os # Import local modules from photoshop import Session with Session(action="new_document") as ps: doc = ps.active_document doc.info.author = os.getenv("USERNAME") doc.info.provinceState = "Beijing" doc.info.title = "My Demo" print("Print all metadata of current active document.") ps.echo(doc.info) Get Document By Name
"""Example of retrieving a Photoshop document by its name. This example demonstrates how to: 1. Access documents in the Photoshop application 2. Find a specific document by its name 3. Handle cases when the document doesn't exist Key concepts: - Using the documents collection - Document name comparison - Error handling for missing documents """ # Import local modules from photoshop import Session with Session() as ps: # Try to get document named 'test.psd' for doc in ps.app.documents: if doc.name == "test.psd": ps.echo(doc.name) break else: ps.echo("Document not found!") Add Start Application Event
"""Add event for Photoshop start application. In the current example, every time we start photoshop it will alert "Start Application Event". Just like you manually in Script> Script Events Manager to enable the event. """ # Import built-in modules import os from tempfile import mkdtemp # Import local modules from photoshop import Session with Session() as ps: root = mkdtemp() jsx_file = os.path.join(root, "event.jsx") with open(jsx_file, "w") as f: f.write('alert("Start Application event.")') ps.app.notifiers.add(ps.EventID.Notify, jsx_file) print("Add event done.") Apply Crystallize Filter Action
""" This script demonstrates how you can use the action manager to execute the Crystallize filter. In order to find all the IDs, see https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin # noqa: E501 This blog here explains what a script listener is http://blogs.adobe.com/crawlspace/2006/05/installing_and_1.html References: https://github.com/lohriialo/photoshop-scripting-python/blob/master/ApplyCrystallizeFilterAction.py """ # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() with Session(PSD_FILE["layer_comps.psd"], "open") as ps: active_document = ps.active_document nLayerSets = active_document.layerSets print(f"The total amount of current layerSet (Group) is " f"{len(nLayerSets)}.") nArtLayers = active_document.layerSets.item(len(nLayerSets)).artLayers # get the last layer in LayerSets active_document.activeLayer = active_document.layerSets.item(len(nLayerSets)).artLayers.item(len(nArtLayers)) def applyCrystallize(cellSize): cellSizeID = ps.app.CharIDToTypeID("ClSz") eventCrystallizeID = ps.app.CharIDToTypeID("Crst") filterDescriptor = ps.ActionDescriptor filterDescriptor.putInteger(cellSizeID, cellSize) ps.app.executeAction(eventCrystallizeID, filterDescriptor) applyCrystallize(25) print("Apply crystallize done.") Revert Changes
"""This example demonstrates how to roll back history.""" # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document old_state = doc.activeHistoryState print(old_state.name) doc.artLayers.add() last_state = doc.activeHistoryState print(last_state.name) doc.activeHistoryState = old_state print(doc.activeHistoryState.name) Selection Stroke
"""Example of creating and modifying selection strokes in Photoshop. This example demonstrates how to: 1. Create selections with specific shapes 2. Apply strokes to selections 3. Configure stroke options 4. Work with stroke colors and widths Key concepts: - Selection creation - Stroke application - Stroke customization - Color management """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create a rectangular selection doc.selection.select([ [100, 100], [400, 100], [400, 300], [100, 300] ]) # Create stroke color stroke_color = ps.SolidColor() stroke_color.rgb.red = 255 stroke_color.rgb.green = 0 stroke_color.rgb.blue = 0 # Apply stroke to selection doc.selection.stroke( stroke_color, # Color to use width=2, # Stroke width in pixels location=ps.StrokeLocation.Inside, blendMode=ps.ColorBlendMode.Normal, opacity=100 ) # Create circular selection doc.selection.selectElliptical( left=200, top=200, width=200, height=200 ) # Change stroke color stroke_color.rgb.blue = 255 # Apply different stroke doc.selection.stroke( stroke_color, width=5, location=ps.StrokeLocation.Center, blendMode=ps.ColorBlendMode.Normal, opacity=75 ) # Clear selection doc.selection.deselect() Cropping
"""A cropping example.""" # Import local modules from photoshop import Session with Session(action="new_document") as ps: ps.active_document.crop(bounds=[100, 12, 354, 246], width=1920, height=1080) Photoshop Session
"""Add slate information dynamically.""" # Import built-in modules from datetime import datetime import os from tempfile import mkdtemp # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() file_path = PSD_FILE["slate_template.psd"] with Session(file_path, action="open", auto_close=True) as ps: layer_set = ps.active_document.layerSets.getByName("template") data = { "project name": "test_project", "datetime": datetime.today().strftime("%Y-%m-%d"), } for layer in layer_set.layers: if layer.kind == ps.LayerKind.TextLayer: layer.textItem.contents = data[layer.textItem.contents.strip()] jpg_file = os.path.join(mkdtemp("photoshop-python-api"), "slate.jpg") ps.active_document.saveAs(jpg_file, ps.JPEGSaveOptions()) os.startfile(jpg_file) Toggle Proof Colors
"""Toggle the proof color. Like operating in the menu: **View** > **Proof Colors** (Ctrl + Y) """ # Import local modules from photoshop import Session with Session() as ps: ps.app.runMenuItem(ps.app.stringIDToTypeID("toggleProofColors")) Session Callback
"""Example of using callbacks with Photoshop sessions. This example demonstrates how to: 1. Set up session callbacks 2. Handle Photoshop events 3. Manage callback execution 4. Process event data Key concepts: - Event handling - Callbacks - Session management - Event processing """ # Import local modules from photoshop import Session def on_close(): """Callback function for session close event.""" print("Session is closing") with Session(callback=on_close) as ps: ps.echo("Working in session...") Current Tool
"""Example of working with Photoshop tools. This example demonstrates how to: 1. Get the current active tool 2. Change tools programmatically 3. Configure tool options 4. Work with tool presets Key concepts: - Tool selection - Tool properties - Tool management - Active tool state """ # Import local modules from photoshop import Session with Session() as ps: # Get current tool current = ps.app.currentTool # Print current tool name ps.echo(f"Current tool: {current}") Enable Generator
"""Enable Generator features.""" # Import local modules from photoshop import Session with Session() as ps: plugin_name = "generator-assets-dummy-menu" generatorDesc = ps.ActionDescriptor generatorDesc.putString(ps.app.stringIDToTypeID("name"), plugin_name) ps.app.executeAction(ps.app.stringIDToTypeID("generateAssets"), generatorDesc) Convert Smartobject To Layer
"""Example of converting between smart objects and regular layers. This example demonstrates how to: 1. Convert layers to smart objects 2. Convert smart objects back to regular layers 3. Manage smart object properties 4. Handle smart object conversions Key concepts: - Smart Objects - Layer conversion - Smart Object properties - Layer types """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create a new layer layer = doc.artLayers.add() layer.name = "Test Layer" # Convert to smart object layer.convertToSmartObject() ps.echo("Layer converted to Smart Object") # Check if it's a smart object if layer.kind == ps.LayerKind.SmartObjectLayer: ps.echo("Layer is now a Smart Object") # Convert back to regular layer layer.rasterize(ps.RasterizeType.EntireLayer) ps.echo("Smart Object converted back to regular layer") Trim
"""A trim example.""" # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() example_file = PSD_FILE["trim.psd"] with Session(example_file, action="open") as ps: ps.active_document.trim(ps.TrimType.TopLeftPixel, True, True, True, True) Apply Filters
"""Example of applying various filters to layers in Photoshop. This example demonstrates how to: 1. Apply different types of Photoshop filters 2. Configure filter parameters 3. Work with filter options 4. Handle filter application to different layer types Key concepts: - Filter types and options - Layer filtering - Parameter configuration - Filter effects management """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document layer = doc.activeLayer # Apply Gaussian Blur filter filter_options = ps.GaussianBlurOptions() filter_options.radius = 10.0 layer.applyGaussianBlur(filter_options) # Create new layer for other filters new_layer = doc.artLayers.add() # Apply Motion Blur motion_options = ps.MotionBlurOptions() motion_options.angle = 45 motion_options.distance = 20 new_layer.applyMotionBlur(motion_options) # Apply Smart Sharpen sharpen_options = ps.SmartSharpenOptions() sharpen_options.amount = 100 sharpen_options.radius = 3.0 sharpen_options.noiseReduction = 20 new_layer.applySmartSharpen(sharpen_options) # Apply Unsharp Mask unsharp_options = ps.UnsharpMaskOptions() unsharp_options.amount = 50 unsharp_options.radius = 2.0 unsharp_options.threshold = 0 new_layer.applyUnsharpMask(unsharp_options) Run Batch
# Import built-in modules import os # Import local modules from photoshop import Session root = "your/images/root" files = [] for name in os.listdir(root): files.append(os.path.join(root, name)) with Session() as api: options = api.BatchOptions() options.destination = 3 options.destinationFolder = "c:\\test" api.app.batch(files=files, actionName="Quadrant Colors", actionSet="Default Actions", options=options) Color
"""Example of working with colors in Photoshop. This example demonstrates how to: 1. Create and modify solid colors 2. Work with different color models (RGB, CMYK, HSB) 3. Set foreground and background colors 4. Compare color values Key concepts: - Color models - Color manipulation - Color space conversion - Color comparison """ # Import local modules from photoshop import Session with Session() as ps: # Create a new RGB color rgb_color = ps.SolidColor() rgb_color.rgb.red = 255 rgb_color.rgb.green = 0 rgb_color.rgb.blue = 0 # Create a new CMYK color cmyk_color = ps.SolidColor() cmyk_color.cmyk.cyan = 0 cmyk_color.cmyk.magenta = 100 cmyk_color.cmyk.yellow = 100 cmyk_color.cmyk.black = 0 # Set as foreground color ps.app.foregroundColor = rgb_color # Create HSB color hsb_color = ps.SolidColor() hsb_color.hsb.hue = 360 hsb_color.hsb.saturation = 100 hsb_color.hsb.brightness = 100 # Set as background color ps.app.backgroundColor = hsb_color Rotate Layer
"""Example of rotating layers in Photoshop. This example demonstrates how to: 1. Rotate layers by specific angles 2. Apply different rotation methods 3. Handle layer transformations 4. Preserve layer properties during rotation Key concepts: - Layer rotation - Transform operations - Angle calculations - Layer positioning """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document layer = doc.activeLayer # Store original bounds bounds = layer.bounds # Calculate center point center_x = (bounds[0] + bounds[2]) / 2 center_y = (bounds[1] + bounds[3]) / 2 # Rotate layer by 45 degrees layer.rotate(45.0, ps.AnchorPosition.MiddleCenter) # Create new layer and rotate it new_layer = doc.artLayers.add() new_layer.name = "Rotated Layer" # Rotate new layer by 90 degrees new_layer.rotate(90.0, ps.AnchorPosition.MiddleCenter) # Move layer to original center new_layer.translate(center_x - new_layer.bounds[0], center_y - new_layer.bounds[1]) Export Artboards
"""Example of how to export artboards from a PSD file. This script demonstrates how to: 1. Identify artboard layers in a PSD file 2. Export each artboard as a separate image """ # Import built-in modules import os.path from pathlib import Path from typing import List from typing import Union # Import local modules from photoshop import Session from photoshop.api._artlayer import ArtLayer from photoshop.api._layerSet import LayerSet from photoshop.api.enumerations import LayerKind def is_artboard(layer: Union[ArtLayer, LayerSet], ps) -> bool: """Check if a layer is an artboard. Args: layer: Photoshop layer object (ArtLayer or LayerSet) ps: Photoshop session object Returns: bool: True if the layer is an artboard, False otherwise """ try: return layer.kind == LayerKind.ArtboardLayer except Exception as e: print(f"Error checking layer {layer.name}: {str(e)}") # Fallback to checking layer name return "Artboard" in layer.name def get_all_layers(doc) -> List[Union[ArtLayer, LayerSet]]: """Recursively get all layers from document, including nested layers. Args: doc: Photoshop document object Returns: List[Union[ArtLayer, LayerSet]]: List of all layers """ def _get_layers(layer_container) -> List[Union[ArtLayer, LayerSet]]: layers = [] # Get art layers for layer in layer_container.artLayers: layers.append(layer) # Get layer sets and their children for layer_set in layer_container.layerSets: layers.append(layer_set) layers.extend(_get_layers(layer_set)) return layers return _get_layers(doc) def get_artboard_layers(doc, artboard_name: str) -> List[Union[ArtLayer, LayerSet]]: """Get all layers that belong to an artboard. Args: doc: Photoshop document object artboard_name: Name of the artboard Returns: List[Union[ArtLayer, LayerSet]]: List of layers that belong to this artboard """ try: # Get all layers in the document all_layers = [] for layer in doc.artLayers: all_layers.append(layer) for layer in doc.layerSets: all_layers.append(layer) # Get the artboard layer artboard = None for layer in all_layers: if layer.name == artboard_name: artboard = layer break if not artboard: return [] # Get all layers that belong to this artboard artboard_layers = [] for layer in all_layers: if layer.name != artboard_name: try: # Check if layer is visible and within artboard bounds if layer.visible and isinstance(layer, ArtLayer): artboard_layers.append(layer) except Exception as e: print(f"Error checking layer {layer.name}: {str(e)}") continue return artboard_layers except Exception as e: print(f"Error getting artboard layers: {str(e)}") return [] def export_artboards(psd_path: str, output_dir: str) -> None: """Export all artboards in a PSD file as separate images. Args: psd_path (str): Path to the PSD file output_dir (str): Directory to save the exported images """ with Session() as ps: try: # Open the PSD file ps.app.open(os.path.abspath(psd_path)) doc = ps.active_document # Create output directory if it doesn't exist Path(output_dir).mkdir(parents=True, exist_ok=True) # Get all layers including nested ones all_layers = get_all_layers(doc) print(f"Found {len(all_layers)} total layers:") for layer in all_layers: layer_type = "LayerSet" if isinstance(layer, LayerSet) else "ArtLayer" is_ab = "Artboard" if is_artboard(layer, ps) else "Regular Layer" print(f"Layer: {layer.name} ({layer_type} - {is_ab})") # Iterate through all layers for layer in all_layers: if is_artboard(layer, ps): print(f"\nProcessing artboard: {layer.name}") # Export artboard using JavaScript output_path = os.path.abspath(str(Path(output_dir) / f"{layer.name}.png")) # Convert Windows path to JavaScript path format js_path = output_path.replace("\\", "/") js_code = """ function exportArtboard(filePath, artboardName) { var doc = app.activeDocument; var artboard = null; // Find the artboard for (var i = 0; i < doc.layers.length; i++) { if (doc.layers[i].name === '%s') { artboard = doc.layers[i]; break; } } if (!artboard) return; // Save the current state var docState = doc.activeHistoryState; try { // Hide all layers for (var i = 0; i < doc.layers.length; i++) { doc.layers[i].visible = false; } // Show only the artboard and its contents artboard.visible = true; // Save as PNG var pngFile = new File('%s'); var pngOptions = new PNGSaveOptions(); pngOptions.interlaced = false; pngOptions.compression = 9; pngOptions.transparency = true; doc.saveAs(pngFile, pngOptions, true, Extension.LOWERCASE); // Restore the document state doc.activeHistoryState = docState; } catch (e) { // Restore the document state in case of error doc.activeHistoryState = docState; throw e; } } exportArtboard('%s', '%s'); """ % (layer.name, js_path, js_path, layer.name) ps.app.eval_javascript(js_code) print(f"Exported {layer.name} to {output_path}") except Exception as e: print(f"Error processing PSD file: {str(e)}") raise if __name__ == "__main__": # Example usage current_dir = os.path.dirname(os.path.abspath(__file__)) psd_path = os.path.join(current_dir, "files", "artboard_example.psd") # Use absolute path output_dir = os.path.join(current_dir, "output", "artboards") # Use absolute path export_artboards(psd_path, output_dir) Load Selection
"""Example of loading and working with selections in Photoshop. This example demonstrates how to: 1. Create and save selections 2. Load saved selections 3. Modify selection channels 4. Combine multiple selections Key concepts: - Selection channels - Channel operations - Selection saving/loading - Selection modification """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create initial selection doc.selection.select([ [100, 100], [300, 100], [300, 300], [100, 300] ]) # Save selection to channel doc.channels.add() doc.selection.store(doc.channels[-1]) # Deselect everything doc.selection.deselect() # Create another selection doc.selection.select([ [200, 200], [400, 200], [400, 400], [200, 400] ]) # Save to another channel doc.channels.add() doc.selection.store(doc.channels[-1]) # Load first selection doc.selection.load(doc.channels[-2]) # Combine with second selection doc.selection.combine(doc.channels[-1], ps.SelectionType.ExtendSelection) # Clean up - delete added channels doc.channels[-1].remove() doc.channels[-1].remove() Eval Javascript
"""Example of executing JavaScript code in Photoshop. This example demonstrates how to: 1. Execute JavaScript commands 2. Interact with Photoshop's scripting engine 3. Handle JavaScript results 4. Pass data between Python and JavaScript Key concepts: - JavaScript execution - Script integration - Data exchange - Command execution """ # Import local modules from photoshop import Session with Session() as ps: # Execute JavaScript command js_code = "app.documents.length" result = ps.app.eval_javascript(js_code) ps.echo(f"Number of open documents: {result}") Open Psd
# Import local modules from photoshop import Session import photoshop.api as ps # style 1 app = ps.Application() app.load("your/psd/or/psb/file_path.psd") # style 2 with Session("your/psd/or/psb/file_path.psd", action="open") as ps: ps.echo(ps.active_document.name) Create New Document
"""Example of creating a new document in Photoshop. This example demonstrates how to: 1. Create a new document with specific dimensions 2. Set document properties like name and mode 3. Work with document units and resolution Key concepts: - Document creation - Document properties - Color mode settings """ # Import local modules from photoshop import Session with Session() as ps: # Create a new document with specific dimensions doc = ps.app.documents.add( width=1920, height=1080, resolution=72, name="New Document Example" ) Create Thumbnail
"""Create a thumbnail image for currently active document. You can use the thumbnail image to upload to Shotgun or Ftrack. """ # Import built-in modules import os from tempfile import mkdtemp # Import local modules from photoshop import Session def create_thumbnail(output_path=None, max_resolution=512): """Create a thumbnail image for currently active document. Args: output_path (str): The absolute output path of the thumbnail image. The default is to output to a temporary folder. max_resolution (int): The max resolution of the thumbnail. The default is `512`. Returns: str: The absolute output path of the thumbnail image. """ output_path = output_path or os.path.join(mkdtemp(), "thumb.jpg") with Session(auto_close=True) as ps: orig_name = ps.active_document.name width_str = ps.active_document.width height_str = ps.active_document.height thumb_name = f"{orig_name}_thumb" max_resolution = width_str / max_resolution thumb_width = int(width_str / max_resolution) thumb_height = int(height_str / max_resolution) thumb_doc = ps.active_document.duplicate(thumb_name) thumb_doc.resizeImage(thumb_width, thumb_height - 100) thumb_doc.saveAs(output_path, ps.JPEGSaveOptions(), asCopy=True) thumb_doc.close() return output_path if __name__ == "__main__": thumb_file = create_thumbnail() print(f"Save thumbnail file to {thumb_file}.") Do Photoshop Action
"""Example of executing Photoshop actions. This example demonstrates how to: 1. Play recorded Photoshop actions 2. Work with action sets 3. Handle action execution 4. Manage action parameters Key concepts: - Action playback - Action sets - Action execution - Automation """ # Import local modules from photoshop import Session with Session() as ps: # Play default Photoshop action ps.app.doAction("action_name", "set_name") Save As Pdf
"""Example of saving documents as PDF files in Photoshop. This example demonstrates how to: 1. Save documents in PDF format 2. Configure PDF save options 3. Handle PDF compression settings 4. Set PDF compatibility options Key concepts: - PDF export - Save options - File compression - PDF settings """ # Import built-in modules import os # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Configure PDF save options pdf_options = ps.PDFSaveOptions() pdf_options.alphaChannels = True pdf_options.embedColorProfile = True pdf_options.embedFonts = True pdf_options.layers = False pdf_options.optimizeForWeb = True pdf_options.view = False # Generate output path output_path = os.path.join(os.path.dirname(__file__), "output.pdf") # Save document as PDF doc.saveAs(output_path, pdf_options, True) Delete And Fill Selection
"""This script demonstrates how to delete and fill a selection in one operation.""" # Import built-in modules import os # Import third-party modules from photoshop import Session from photoshop.api import SolidColor import photoshop.api as ps # Import local modules from _psd_files import get_psd_files def delete_and_fill_selection(doc, fill_type, mode=None, opacity=None, preserve_transparency=None): """Delete current selection and fill it with specified color. Args: doc: The active document. fill_type (SolidColor): The color to fill the selection with. mode (ColorBlendMode, optional): The color blend mode. opacity (int, optional): The opacity value. preserve_transparency (bool, optional): If true, preserves transparency. """ # First fill the selection doc.selection.fill(fill_type, mode, opacity, preserve_transparency) # Then deselect doc.selection.deselect() def main(): """Create a selection and fill it with a solid color.""" psd_file = get_psd_files()["export_layers_as_png.psd"] # Initialize Photoshop application app = ps.Application() # Open the test file if not os.path.exists(psd_file): raise FileNotFoundError(f"Test file not found: {psd_file}") app.load(psd_file) # Get the active document doc = app.activeDocument # Create a rectangular selection doc.selection.select(((100, 100), (400, 100), (400, 300), (100, 300))) # Create a solid color (red in this case) red_color = SolidColor() red_color.rgb.red = 255 red_color.rgb.green = 0 red_color.rgb.blue = 0 # Delete and fill the selection delete_and_fill_selection(doc, red_color, opacity=80) # Save the changes doc.save() print("Selection has been filled with red color.") if __name__ == "__main__": main() Fill Selection
"""Example of filling selections in Photoshop. This example demonstrates how to: 1. Create and modify selections 2. Fill selections with colors 3. Work with selection options 4. Apply different fill methods Key concepts: - Selection tools - Fill operations - Color fills - Selection modification - Fill opacity and blending """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create a rectangular selection doc.selection.select([ [100, 100], [300, 100], [300, 200], [100, 200] ]) # Create fill color fill_color = ps.SolidColor() fill_color.rgb.red = 255 fill_color.rgb.green = 0 fill_color.rgb.blue = 0 # Fill the selection doc.selection.fill(fill_color) # Deselect doc.selection.deselect() # Create another selection and fill with opacity doc.selection.select([ [150, 150], [350, 150], [350, 250], [150, 250] ]) fill_color.rgb.blue = 255 doc.selection.fill(fill_color, ps.ColorBlendMode.Normal, 50) # Clear selection doc.selection.deselect() Emboss Action
# Import local modules from photoshop import Session with Session() as ps: app = ps.app for index, x in enumerate(range(50)): # Execute an existing action from action palette. idPly = app.charIDToTypeID("Ply ") desc8 = ps.ActionDescriptor() idnull = app.charIDToTypeID("null") ref3 = ps.ActionReference() idActn = app.charIDToTypeID("Actn") ref3.putName(idActn, "Sepia Toning (layer)") idASet = app.charIDToTypeID("ASet") ref3.PutName(idASet, "Default Actions") desc8.putReference(idnull, ref3) app.executeAction(idPly, desc8, ps.DialogModes.DisplayNoDialogs) # Create solid color fill layer. idMk = app.charIDToTypeID("Mk ") desc21 = ps.ActionDescriptor() idNull = app.charIDToTypeID("null") ref12 = ps.ActionReference() idContentLayer1 = app.stringIDToTypeID("contentLayer") ref12.putClass(idContentLayer1) desc21.putReference(idNull, ref12) idUsng = app.charIDToTypeID("Usng") desc22 = ps.ActionDescriptor() idType = app.charIDToTypeID("Type") desc23 = ps.ActionDescriptor() idClr = app.charIDToTypeID("Clr ") desc24 = ps.ActionDescriptor() idRd = app.charIDToTypeID("Rd ") desc24.putDouble(idRd, index) idGrn = app.charIDToTypeID("Grn ") desc24.putDouble(idGrn, index) idBl = app.charIDToTypeID("Bl ") desc24.putDouble(idBl, index) idRGBC = app.charIDToTypeID("RGBC") desc23.putObject(idClr, idRGBC, desc24) idSolidColorLayer = app.StringIDToTypeID("solidColorLayer") desc22.putObject(idType, idSolidColorLayer, desc23) idContentLayer2 = app.StringIDToTypeID("contentLayer") desc21.putObject(idUsng, idContentLayer2, desc22) app.executeAction(idMk, desc21, ps.DialogModes.DisplayNoDialogs) # Select mask. idSlct = app.charIDToTypeID("slct") desc38 = ps.ActionDescriptor() idNull1 = app.charIDToTypeID("null") ref20 = ps.ActionReference() idChnl1 = app.charIDToTypeID("Chnl") idChnl2 = app.charIDToTypeID("Chnl") idMsk = app.charIDToTypeID("Msk ") ref20.putEnumerated(idChnl1, idChnl2, idMsk) desc38.putReference(idNull1, ref20) idMkVs = app.charIDToTypeID("MkVs") desc38.putBoolean(idMkVs, False) app.executeAction(idSlct, desc38, ps.DialogModes.DisplayNoDialogs) app.activeDocument.activeLayer.invert() Add Slate
"""Add slate information dynamically. - Open template. - Update info. - Save as jpg. - Close current document. """ # Import built-in modules from datetime import datetime import os from tempfile import mkdtemp # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() slate_template = PSD_FILE["slate_template.psd"] with Session(slate_template, action="open", auto_close=True) as ps: layer_set = ps.active_document.layerSets.getByName("template") data = { "project name": "test_project", "datetime": datetime.today().strftime("%Y-%m-%d"), } for layer in layer_set.layers: if layer.kind == ps.LayerKind.TextLayer: layer.textItem.contents = data[layer.textItem.contents.strip()] jpg_file = os.path.join(mkdtemp("photoshop-python-api"), "slate.jpg") ps.active_document.saveAs(jpg_file, ps.JPEGSaveOptions()) print(f"Save jpg to {jpg_file}") os.startfile(jpg_file) Save As Tga
"""Example of saving documents as TGA files in Photoshop. This example demonstrates how to: 1. Save documents in TGA format 2. Configure TGA save options 3. Handle alpha channels 4. Set compression options Key concepts: - TGA export - Save options - Alpha channel handling - Resolution settings """ # Import built-in modules import os # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Configure TGA save options tga_options = ps.TargaSaveOptions() tga_options.alphaChannels = True tga_options.resolution = ps.TargaBitsPerPixels.TWENTYFOUR tga_options.rleCompression = True # Generate output path output_path = os.path.join(os.path.dirname(__file__), "output.tga") # Save document as TGA doc.saveAs(output_path, tga_options, True) # Save another version with different settings tga_options.resolution = ps.TargaBitsPerPixels.THIRTYTWO output_path_32 = os.path.join(os.path.dirname(__file__), "output_32bit.tga") doc.saveAs(output_path_32, tga_options, True) Compare Colors
"""Example of comparing colors in Photoshop. This example demonstrates how to: 1. Compare colors across different color models 2. Convert between color spaces 3. Check color equality 4. Work with color tolerances Key concepts: - Color comparison - Color space conversion - Color equality testing - Color model differences """ # Import local modules from photoshop import Session with Session() as ps: # Create two colors for comparison color1 = ps.SolidColor() color1.rgb.red = 255 color1.rgb.green = 0 color1.rgb.blue = 0 color2 = ps.SolidColor() color2.rgb.red = 255 color2.rgb.green = 0 color2.rgb.blue = 0 # Compare colors is_same = (color1.rgb.red == color2.rgb.red and color1.rgb.green == color2.rgb.green and color1.rgb.blue == color2.rgb.blue) ps.echo(f"Colors are {'same' if is_same else 'different'}") Set Active Layer
""" References: https://github.com/lohriialo/photoshop-scripting-python/blob/master/ActiveLayer.py """ # Import local modules import photoshop.api as ps app = ps.Application() if app.documents.length < 1: docRef = app.documents.add() else: docRef = app.activeDocument if docRef.layers.length < 2: docRef.artLayers.add() activeLayerName = docRef.activeLayer.name if docRef.activeLayer.name != docRef.layers.item(docRef.layers.length).name: docRef.activeLayer = docRef.layers.item(docRef.layers.length) else: docRef.activeLayer = docRef.layers.item(1) Export Document
"""Example of exporting a Photoshop document to different formats. This example demonstrates how to: 1. Save documents in different formats (JPG, PNG) 2. Configure export quality settings 3. Handle file paths and naming 4. Use save options for different formats Key concepts: - File format conversion - Export quality control - Save options configuration - File path handling """ # Import built-in modules import os # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Get the directory of current script current_dir = os.path.dirname(__file__) # Save as JPG with high quality jpg_opt = ps.JPEGSaveOptions(quality=12) jpg_path = os.path.join(current_dir, "output.jpg") doc.saveAs(jpg_path, jpg_opt) # Save as PNG with transparency png_opt = ps.PhotoshopSaveOptions() png_path = os.path.join(current_dir, "output.png") doc.saveAs(png_path, png_opt) Change Color Of Background And Foreground
"""Example of changing background and foreground colors in Photoshop. This example demonstrates how to: 1. Set foreground and background colors 2. Work with color swatches 3. Switch between foreground and background colors 4. Reset colors to default values Key concepts: - Color management - Foreground/background colors - Color swatches - Default colors """ # Import local modules from photoshop import Session with Session() as ps: # Create new colors fg_color = ps.SolidColor() fg_color.rgb.red = 255 fg_color.rgb.green = 0 fg_color.rgb.blue = 0 bg_color = ps.SolidColor() bg_color.rgb.red = 0 bg_color.rgb.green = 0 bg_color.rgb.blue = 255 # Set foreground and background colors ps.app.foregroundColor = fg_color ps.app.backgroundColor = bg_color # Print current colors ps.echo(f"Foreground RGB: {ps.app.foregroundColor.rgb.red}, " f"{ps.app.foregroundColor.rgb.green}, " f"{ps.app.foregroundColor.rgb.blue}") ps.echo(f"Background RGB: {ps.app.backgroundColor.rgb.red}, " f"{ps.app.backgroundColor.rgb.green}, " f"{ps.app.backgroundColor.rgb.blue}") Smart Sharpen
"""Example of applying Smart Sharpen filter in Photoshop. This example demonstrates how to: 1. Apply Smart Sharpen filter with various settings 2. Configure sharpening parameters 3. Handle different sharpening methods 4. Process multiple layers Key concepts: - Smart Sharpen filter - Filter parameters - Image enhancement - Layer processing """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document layer = doc.activeLayer # Configure Smart Sharpen options options = ps.SmartSharpenOptions() options.amount = 100.0 options.radius = 3.0 options.noiseReduction = 20 options.removeMotionBlur = False options.angle = 0 options.moreAccurate = True # Apply Smart Sharpen layer.applySmartSharpen( amount=options.amount, radius=options.radius, noiseReduction=options.noiseReduction, removeMotionBlur=options.removeMotionBlur, angle=options.angle, moreAccurate=options.moreAccurate ) # Create a copy with different settings new_layer = layer.duplicate() new_layer.name = "Sharp Copy" # Apply stronger sharpening options.amount = 150.0 options.radius = 4.0 new_layer.applySmartSharpen( amount=options.amount, radius=options.radius, noiseReduction=options.noiseReduction, removeMotionBlur=options.removeMotionBlur, angle=options.angle, moreAccurate=options.moreAccurate ) Operate Channels
"""Example of working with channels in Photoshop. This example demonstrates how to: 1. Access and manipulate color channels 2. Create and modify alpha channels 3. Work with channel visibility 4. Handle channel operations Key concepts: - Channel management - Alpha channels - Channel visibility - Color separation """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # List all channels for channel in doc.channels: ps.echo(f"Channel: {channel.name}") # Create a new alpha channel new_channel = doc.channels.add() new_channel.name = "Custom Alpha" # Duplicate a channel if len(doc.channels) > 0: duplicate = doc.channels[0].duplicate() duplicate.name = "Channel Copy" # Toggle channel visibility for channel in doc.channels: channel.visible = True Export Layers Use Export Options Saveforweb
"""Export every layer as a .png file use `ExportOptionsSaveForWeb`.""" # Import built-in modules import os # Import third-party modules import examples._psd_files as psd # Import from examples. # Import local modules from photoshop import Session PSD_FILE = psd.get_psd_files() def hide_all_layers(layers): for layer in layers: layer.visible = False def main(): psd_file = PSD_FILE["export_layers_as_png.psd"] with Session(psd_file, action="open") as ps: doc = ps.active_document options = ps.ExportOptionsSaveForWeb() layers = doc.artLayers for layer in layers: hide_all_layers(layers) layer.visible = True layer_path = os.path.join(doc.path, layer.name) print(layer_path) if not os.path.exists(layer_path): os.makedirs(layer_path) image_path = os.path.join(layer_path, f"{layer.name}.png") doc.exportDocument(image_path, exportAs=ps.ExportType.SaveForWeb, options=options) ps.alert("Task done!") ps.echo(doc.activeLayer) if __name__ == "__main__": main() New Document
# Create a new Photoshop document with diminsions 4 inches by 4 inches. # Import local modules import photoshop.api as ps # Start up Photoshop application app = ps.Application() start_ruler_units = app.preferences.rulerUnits app.preferences.rulerUnits = ps.Units.Pixels # Create the document docRef = app.documents.add(1920, 1080, 72.0, "My New Document") # Make sure to set the ruler units prior to creating the document. app.preferences.rulerUnits = start_ruler_units Export Layers As Png
"""Example of exporting individual layers as PNG files. This example demonstrates how to: 1. Export each layer of a document as a separate PNG file 2. Handle layer visibility during export 3. Manage layer selection and activation 4. Configure export settings for PNG format Key concepts: - Layer iteration - Visibility management - PNG export settings - File naming conventions - Layer selection """ # Import built-in modules import os # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Store original layer visibilities layer_visibilities = [] for layer in doc.layers: layer_visibilities.append(layer.visible) layer.visible = False try: # Export each layer individually for i, layer in enumerate(doc.layers): # Show only current layer layer.visible = True # Configure PNG save options options = ps.PNGSaveOptions() options.interlaced = False # Generate unique filename for each layer file_path = os.path.join( os.path.dirname(__file__), f"layer_{i}_{layer.name}.png" ) # Save the file doc.saveAs(file_path, options, True) # Hide the layer again layer.visible = False finally: # Restore original layer visibilities for layer, visibility in zip(doc.layers, layer_visibilities): layer.visible = visibility Link Layer
"""Example of linking layers in Photoshop. This example demonstrates how to: 1. Link multiple layers together 2. Manage linked layers 3. Check layer link status 4. Modify linked layer properties Key concepts: - Layer linking - Group operations - Layer management - Link status """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create test layers layer1 = doc.artLayers.add() layer1.name = "Layer 1" layer2 = doc.artLayers.add() layer2.name = "Layer 2" layer3 = doc.artLayers.add() layer3.name = "Layer 3" # Link layers layer1.link(layer2) layer2.link(layer3) # Check link status ps.echo(f"Layer 1 linked: {layer1.linked}") ps.echo(f"Layer 2 linked: {layer2.linked}") ps.echo(f"Layer 3 linked: {layer3.linked}") # Move linked layers together layer1.translate(100, 100) Session New Document
"""Action for create new document and print new document name.""" # Import local modules from photoshop import Session with Session(action="new_document") as ps: ps.echo(ps.active_document.name) Save To Psd
"""Example of saving documents as PSD files in Photoshop. This example demonstrates how to: 1. Save documents in PSD format 2. Configure PSD save options 3. Preserve layer information 4. Handle compatibility settings Key concepts: - PSD format - Layer preservation - Save options - File compatibility """ # Import built-in modules import os # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Configure PSD save options psd_options = ps.PhotoshopSaveOptions() psd_options.alphaChannels = True psd_options.annotations = True psd_options.layers = True psd_options.spotColors = True # Generate output path output_path = os.path.join(os.path.dirname(__file__), "output.psd") # Save document as PSD doc.saveAs(output_path, psd_options, True) Session Hello World
"""Add slate information dynamically.""" # Import built-in modules import os from tempfile import mkdtemp # Import local modules from photoshop import Session with Session() as adobe: doc = adobe.app.documents.add(2000, 2000) text_color = adobe.SolidColor() text_color.rgb.red = 255 new_text_layer = doc.artLayers.add() new_text_layer.kind = adobe.LayerKind.TextLayer new_text_layer.textItem.contents = "Hello, World!" new_text_layer.textItem.position = [160, 167] new_text_layer.textItem.size = 40 new_text_layer.textItem.color = text_color options = adobe.JPEGSaveOptions(quality=1) jpg_file = os.path.join(mkdtemp("photoshop-python-api"), "hello_world.jpg") doc.saveAs(jpg_file, options, asCopy=True) adobe.app.doJavaScript(f'alert("save to jpg: {jpg_file}")') Creating A Layer
"""Example of creating and manipulating layers in Photoshop. This example demonstrates how to: 1. Create different types of layers 2. Set layer properties and attributes 3. Organize layers in the document 4. Apply basic layer effects Key concepts: - Layer creation - Layer types (art layers, text layers) - Layer properties - Layer organization """ # Import local modules from photoshop import Session with Session() as ps: doc = ps.active_document # Create a new art layer new_layer = doc.artLayers.add() # Set layer properties new_layer.name = "New Art Layer" new_layer.opacity = 75 new_layer.visible = True # Create a text layer text_layer = doc.artLayers.add() text_layer.kind = ps.LayerKind.TextLayer # Configure text properties text_item = text_layer.textItem text_item.contents = "Sample Text" text_item.size = 72 text_item.position = [100, 100] # Move layers in stack new_layer.move(text_layer, ps.ElementPlacement.PlaceAfter) Last update: 2025-05-19
Created: 2025-05-19
Created: 2025-05-19