Search code examples
scriptinggimpsave-imagepython-fu

GIMP Python-fu exporting file only exports transparent layer


I am having issues saving images in python via GIMP. I can get the image and apply the effects I want, but when I go to save, it only saves one layer and not everything (NOTE: The background is transparent) and because the background is transparent, I cannot get it to save anything besides the transparent background. The code I am using is posted below:

image_array = gimp.image_list()
i=0
for image in image_array:
    img = image_array[i]
    layers = img.layers
    last_layer = len(layers)-1
    try:
        disable=pdb.gimp_image_undo_disable(img)
        pdb.gimp_layer_add_alpha(layers[0])
        drw = pdb.gimp_image_active_drawable(img)
        pdb.plug_in_colortoalpha(img,drw,(0,0,0))
        drw = pdb.gimp_image_active_drawable(img)
        enable = pdb.gimp_image_undo_enable(img)

    except:
        print "ERROR"

    pdb.file_png_save(img, drw, "C:\\Users\\jammer\\Desktop\\test.png",
                      "test.png",0,9,1,1,1,1,1)
    i+=1

I have also tried file_png_save2, but I have a feeling the problem lies in the drw object as I just want to replicate the option of clicking File->Export and saving as PNG without doing that via GUI. I would rather have it save automatically (I have 49 images and each will be named automatically, but first I need to get it to export correctly with one image). as I said before, the code above only exports a transparent background, even changing to a GIF does not resolve the issue. How do I export a file as a PNG while keeping all layers and transparent background?


Solution

  • I found my problem! I was not merging the visible layers and setting that equal to the new layer, which I then used as the "drawable object" when saving the image as a png! I have posted the fixed code below:

    image_array = gimp.image_list()
    i=0
    for image in image_array:
        img = image_array[i]
        layers = img.layers
        last_layer = len(layers)-1
        try:
            disable=pdb.gimp_image_undo_disable(img)
            pdb.gimp_layer_add_alpha(layers[0])
            drw = pdb.gimp_image_active_drawable(img)
            pdb.plug_in_colortoalpha(img,drw,(0,0,0))
            layer = pdb.gimp_image_merge_visible_layers(img, gimpfu.CLIP_TO_IMAGE)#FIXES PROBLEM OF ONLY EXPORTING TRANSPARENCY!
            enable = pdb.gimp_image_undo_enable(img)
    
        except:
            print "ERROR"
    
        pdb.file_png_save2(img, layer, "C:\\Users\\jammer\\Desktop\\test.png","test.png",1,9,1,1,1,1,1,0,1)
        i+=1