如何使用 gimp 的脚本 fu 保存(导出)所有图层?



使用gimp-fu,我可以保存一个层的内容(至少,这是我解释gimp_file_save的定义的方式,因为它采用了参数drawable)。

现在,我有以下脚本:

from gimpfu import *
def write_text():
    width  = 400
    height = 100
    img = gimp.Image(width, height, RGB)
    img.disable_undo()

    gimp.set_foreground( (255, 100, 20) )
    gimp.set_background( (  0,  15, 40) )
    background_layer = gimp.Layer(
                           img,
                           'Background',
                           width,
                           height,
                           RGB_IMAGE,
                           100,
                           NORMAL_MODE)
    img.add_layer(background_layer, 0)
    background_layer.fill(BACKGROUND_FILL)
    text_layer = pdb.gimp_text_fontname(
                    img,
                    None,
                    60,
                    40,
                    'Here is some text',
                    0,
                    True,
                    30,
                    PIXELS,
                    'Courier New'
                )
    drawable = pdb.gimp_image_active_drawable(img)
#   Either export text layer ...
#   pdb.gimp_file_save(img, drawable, '/temp/tq84_write_text.png', '?')
#   .... or background layer:
    pdb.gimp_file_save(img, background_layer, '/temp/tq84_write_text.png', '?')
register(
  proc_name     = 'tq84_write_text',
  blurb         = 'tq84_write_text',
  help          = 'Create some text',
  author        = 'Rene Nyffenegger',
  copyright     = 'Rene Nyffenegger',
  date          = '2014',
  label         = '<Toolbox>/Xtns/Languages/Python-Fu/_TQ84/_Text',
  imagetypes    = '',
  params        = [],
  results       = [],
  function      = write_text
)
main()

当我使用pdb.gimp_file_save(img, drawable, '/temp/tq84_write_text.png', '?')保存图像时,它只会导出"文本"层。然而,如果我使用pdb.gimp_file_save(img, background_layer, '/temp/tq84_write_text.png', '?'),它将只导出背景。那么,我如何将两个层导出为一个图像(就像菜单File -> Export As所做的那样)。

即使是所有格式的GIMP文件导出器插件,内部也要做的是:复制图像,合并所有可见层,保存生成的可绘制文件。

这比听起来更容易,占用的资源也更少。实际上,你只需要更换你的存储线

pdb.gimp_file_save(img, background_layer, '/temp/tq84_write_text.png', '?')

通过

new_image = pdb.gimp_image_duplicate(img)
layer = pdb.gimp_image_merge_visible_layers(new_image, CLIP_TO_IMAGE)
pdb.gimp_file_save(new_img, layer, '/temp/tq84_write_text.png', '?')
pdb.gimp_image_delete(new_image)

(最后一个调用只是从程序内存中"删除"新映像,当然释放了资源)

我发现,如果将None作为drawable参数传递给gimp_xcf_save(),GIMP(至少版本2.8)将把图像的所有层保存到XCF文件:

pdb.gimp_xcf_save(0, image, None, 'file.xcf', 'file.xcf')

我发现最简单的方法是将图像压平,然后使用第一层保存:

img.flatten()
pdb.gimp_file_save(img, img.layers[0], 'image.jpg', '?')

最新更新