Skip to content

Instantly share code, notes, and snippets.

@nskrypnik
Created November 19, 2013 13:12
Show Gist options
  • Save nskrypnik/7545153 to your computer and use it in GitHub Desktop.
Save nskrypnik/7545153 to your computer and use it in GitHub Desktop.
import win32com.client
import os
# Change to match your psd file
psdFile = r'E:\topestate\1main.psd'
exportPath = r'E:\topestate\main'
# Photoshop actually exposes several different COM interfaces,
# including one specifically for classes defining export options.
save_options = win32com.client.Dispatch('Photoshop.ExportOptionsSaveForWeb')
save_options.Format = 13 # PNG
save_options.PNG8 = False # Sets it to PNG-24 bit
def hide_layers(layerset):
for layer in layerset.layers:
layer.Visible = False
def walk_through_layers(doc, parent, parent_dir):
hide_layers(parent)
if not os.path.exists(parent_dir):
os.mkdir(parent_dir)
for layer in parent.layers:
# show layer
layer.Visible = True
if layer.typename == 'LayerSet':
layer_dir = os.path.join(parent_dir, layer.name)
# replace spaces for underscore to avoid errors
layer_dir = layer_dir.replace(' ', '_')
walk_through_layers(doc, layer, layer_dir)
elif layer.typename == 'ArtLayer':
png_file = os.path.join(parent_dir, layer.name + '.png')
png_file = png_file.replace(' ', '_')
doc.Export(ExportIn=png_file, ExportAs=2, Options=save_options)
print "Exporiting:", png_file.encode('cp1251')
#hide it again after handling
layer.Visible = False
if __name__ == '__main__':
# COM dispatch for Photoshop
psApp = win32com.client.Dispatch('Photoshop.Application')
# Loop through PSDs we found
doc = psApp.Open(psdFile)
parent_dir = exportPath
parent_dir = parent_dir.replace(' ', '_')
parent = doc
walk_through_layers(doc, parent, parent_dir)
# check for existance of parent dir
doc.Close(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment