Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting active image and layer in Python scripts
#1
If your script is correctly written, in particular its "registration" code, it gets the active image (and the active layer) as parameters:

Code:
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from gimpfu import *

def theCode(theImage,theDrawable):
    pdb.gimp_message('Running on image "%s" (%d) on drawable "%s"' \
        % (theImage.name,theImage.ID,theDrawable.name))
    
register(
    'the_registration_atom',
    'Example registration of a python plugin (short description, pops up in menus)',
    'Example registration of a python plugin (long-winded help that shows in the PDB browser)',
    'Author','Copyright owner','2021',
    'Test menu item',
    '*', # works on all image types
    [
        (PF_IMAGE, "image", "Input image", None),           # Active image if called from the UI
        (PF_DRAWABLE, "drawable", "Input drawable", None),  # Active drawable if called from the UI
        # Other parameters would come here
    ],
    [
        # if you want to be really nice and your script creates image/layers, you can return
        # then and descrive their type here. Makes it easier for other scripts calling your script.
    ],
    theCode,
    menu='<Image>/Test/',
)

main()

   

Notes:
  • An important part is the use of the menu named argument. This makes the registration use the new variant. The older variant where the 7th argument is a full path to the menu item (which is still found in some examples) behaves a bit differently.
  • The "drawable" can be a layer (usual case) but also a layer mask or a channel or even a layer group. Some scripts can work on all types, others may want just a layer. You can use a PF_LAYER instead of a PF_DRAWABLE but the Gimp error message isn't too user-friendly. Better check in your code and react appropriately.
  • Since the script works on a drawable, the menu item is disabled if there is no active drawable in the image (this can happen after you deleted all layers). You can of course remove the drawable argument if the script doesn't require a specific drawable (runs on all layers, or generates new ones)
  • Since the script works on an image, the menu item is disabled if there is no image in Gimp.  You can of course remove the image argument if the script doesn't require a specific image (runs on all images, or loads/generates new ones)
An example script "core" with long-winded comments:
.zip   regdemo.zip (Size: 2.2 KB / Downloads: 35)
Reply


Forum Jump: