Search code examples
pnggimpgimpfuxcf

How to combine several PNG images as layers in a single XCF image?


I have several PNG images, which I need to combine as individual layers in a new GIMP XCF image. I need to perform this task many times, so a script based solution would be best.

So far i tried to play around with the batch mode of GIMP, but failed miserably.


Solution

  • Instead of script-fu, which uses Scheme, I'd recommend using the GIMP-Python binding for this, since it is far easier to manipulate files and listings.

    If you check filters->Python->Console you will b dropped into an interactive mode - at the bottom of it, there will be a "Browse" button which lets you select any of GIMP's procedures in its API and paste it directly in this console.

    There is as an API call to "load a file as a layer" - pdb.gimp_file_load_layer -

    this however, brings the image to memory, but do not add it to the image - you have to call pdb.gimp_image_insert_layer afterwards

    You can type this directly in the interactive console, or,check one of my other GIMP-related answers, or some resource on GIMP-Python on the web to convert it to a plug-in, which won't require pasting this code each time you want to perform the task:

    def open_images_as_layers(img, image_file_list):
        for image_name in image_file_list:
            layer = pdb.gimp_file_load_layer(image_name)
            pdb.gimp_image_insert_layer(img, layer, None, 0)
    
    img = gimp.image_list()[0]
    image_list = "temp1.png temp2.png temp3.png"
    open_images_as_layers(img, image_list.split())
    

    The second to last line img = ... picks a needed reference to an open image in GIMP - you could also create a new image using pdb calls if you'd prefer (example bellow). The file list is a hardcoded space separated string in the snippet above, but you can create the file list in any of the ways allowed by Python. For example, to get all the ".png" file names in a c:\Documents and Settings\My user\Pictures folder, you could do:

    from glob import glob
    image_list = glob("c:/Documents and Settings/My user/Pictures/*png")
    

    To create an image programatically:

    img = gimp.Image(1024, 768)
    pdb.gimp_display_new(img)