2011-07-20 71 views
6

我需要编写一个用于加载PSD photoshop图像的Python程序,该图像具有多个图层并吐出png文件(每个图层一个)。 你可以用Python做到吗?我试过PIL,但似乎没有任何访问图层的方法。帮帮我。 PS。写我自己的PSD加载器和PNG作家已经显示出太慢了。Python PSD图层?

回答

5

使用Gimp-Python? http://www.gimp.org/docs/python/index.html

你不需要Photoshop那种方式,它可以在任何运行Gimp和Python的平台上工作。这是一个很大的依赖,但是一个自由的。

对于PIL做:

from PIL import Image, ImageSequence 
im = Image.open("spam.psd") 
layers = [frame.copy() for frame in ImageSequence.Iterator(im)] 

编辑:OK,找到了解决办法:https://github.com/jerem/psdparse

这将允许你提取从蟒蛇PSD文件层没有任何非Python的东西。

+0

+1对于'psdparse'!似乎OP不必滚动他/她自己的功能:) – rzetterberg

+0

psdparse不起作用。 “不支持的频道数量”错误... – Brock123

+1

我相信,我们已经用尽了所有的选项。你要么必须自己推出,要么使用Gimp-Python。 – agf

2

您可以使用win32com通过Python访问Photoshop。为您的工作 可能的伪代码:

  1. 装入PSD文件
  2. 收集所有层,使所有层的可见= OFF
  3. 打开了一个又一个层,标志着它们可见= ON,并出口到PNG
 

    import win32com.client 
    pApp = win32com.client.Dispatch('Photoshop.Application') 

    def makeAllLayerInvisible(lyrs): 
     for ly in lyrs: 
      ly.Visible = False 

    def makeEachLayerVisibleAndExportToPNG(lyrs): 
     for ly in lyrs: 
      ly.Visible = True 
      options = win32com.client.Dispatch('Photoshop.PNGSaveOptions') 
      options.Interlaced = False 
      tf = 'PNG file name with path' 
      doc.SaveAs(SaveIn=tf,Options=options) 
      ly.Visible = False 

    #pApp.Open(PSD file) 
    doc = pApp.ActiveDocument 
    makeAllLayerInvisible(doc.Layers) 
    makeEachLayerVisibleAndExportToPNG(doc.Layers) 

1

使用了蟒蛇的win32com插件(可在这里:http://python.net/crew/mhammond/win32/)您可以访问Photoshop和轻松地通过你的图层和导出。

这是一个代码示例,它在当前活动的Photoshop文档中的图层上工作,并将它们导出到'save_location'中定义的文件夹中。

from win32com.client.dynamic import Dispatch 

#Save location 
save_location = 'c:\\temp\\' 

#call photoshop 
psApp = Dispatch('Photoshop.Application') 

options = Dispatch('Photoshop.ExportOptionsSaveForWeb') 
options.Format = 13 # PNG 
options.PNG8 = False # Sets it to PNG-24 bit 

doc = psApp.activeDocument 

#Hide the layers so that they don't get in the way when exporting 
for layer in doc.layers: 
    layer.Visible = False 

#Now go through one at a time and export each layer 
for layer in doc.layers: 

    #build the filename 
    savefile = save_location + layer.name + '.png' 

    print 'Exporting', savefile 

    #Set the current layer to be visible   
    layer.visible = True 

    #Export the layer 
    doc.Export(ExportIn=savefile, ExportAs=2, Options=options) 

    #Set the layer to be invisible to make way for the next one 
    layer.visible = False