2011-07-20 77 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