Sep 18, 2009

Writing GIMP 2.6 Python plugins

The GIMP now has Python support in addition to TinyScheme, allowing you to harness the power of GIMP in Python. The following is a simple logo plugin written in Python, usable as a template to write more complex ones. The plugin writes a logo in the bottom-right corner of your image.

#!/usr/bin/python

from gimpfu import *

gettext.install("gimp20-python", gimp.locale_directory, unicode=True)

def mylogo(img, text, opacity, fontname, fontsize):
  gimp.context_push()
  color = (255,255,255)
  pdb.gimp_context_set_foreground(color)
  logo_layer = pdb.gimp_text_fontname(img, None, 0, 0, text, 0, 1,
   fontsize, POINTS, fontname)
  pdb.gimp_layer_set_opacity(logo_layer, opacity)
  x = img.width - logo_layer.width
  y = img.height - logo_layer.height
  pdb.gimp_layer_translate(logo_layer, x, y)
  gimp.context_pop()

register(
  "python-fu-mylogo",
  N_("Add logo to image"),
  "Adds a logo to the bottom-right corner of the image.",
  "", # author name
  "", # copyright owner
  "2009-09-18", # date
  N_("Add logo..."), # text to show in menu
  "RGB*, GRAY*", # image types we can work with
  # Positional parameter definitions, each entry in this format:
  # (TYPE, "name", "caption", default, ...)
  [
    (PF_IMAGE, "image", "Input image", None),
    (PF_STRING, "text", _("Text"), _(u"\xa92009")),
    (PF_SLIDER, "opacity", _("Opacity"), 50, (0,100,1)),
    (PF_FONT, "fontname", _("Font"), "Sans"),
    (PF_INT, "fontsize", _("Size"), 24),
  ],
  # Return values list
  [],
  mylogo, # function name
  # Where to add in menu structure
  # Special tag <Image> indicates you must have an open image
  menu="<Image>/Filters/Render",
  domain=("gimp20-python", gimp.locale_directory)
)
main()

Write ~/.gimp-2.6/plug-ins/mylogo.py and make sure it is executable, or GIMP will ignore it! After restarting GIMP and opening an image file, you will be able to invoke "Add logo..." from the Filters/Render submenu.

All the functions you can use to manipulate an image are in the "Procedural Database", accessible in Python as methods of the pdb object. The list of functions and their documentation can be found using procedure browser: Filters / Python-Fu / Console, click "Browse...". Just remember that the Python names have underscores instead of dashes as illustrated in the code above.

You will also find your own plugins there (search for "mylogo").

References:

No comments:

Post a Comment

Please keep your message on topic if at all possible...