Python PSD层?

2024-06-09 03:59:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个Python程序来加载PSD photoshop图像,它有多个层,并输出png文件(每层一个)。 你能用Python做吗?我试过PIL,但似乎没有任何访问层的方法。救命啊。 写我自己的PSD加载器和png编写器已经证明是太慢了。


Tags: 文件方法图像程序证明pilpngphotoshop
3条回答

你可以使用win32com用Python访问Photoshop。 可能的伪代码:

  1. 加载PSD文件
  2. 收集所有层并使所有层可见=关闭
  3. 依次打开一个图层,将其标记为VISIBLE=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)

使用用于python的win32com插件(此处提供:http://python.net/crew/mhammond/win32/),您可以访问photoshop并轻松地浏览层并导出它们。

下面是一个代码示例,用于当前活动的Photoshop文档中的图层,并将它们导出到“保存位置”中定义的文件夹中。

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

使用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)]

编辑:确定,找到解决方案:https://github.com/jerem/psdparse

这将允许您使用python从psd文件中提取层,而不需要任何非python的东西。

相关问题 更多 >