Basic Perl

Text and images Copyright (C) 1999-2002 Dov Grobgeld and may not be used without permission of the author.

Editor's note: this tutorial was originally written for GIMP 1.2. Parts of it will not work with GIMP 2.x and later versions due to changes in font handling and PDB API.


So far most of the script programming for GIMP has been done using Scheme through Script-Fu. Unfortunately the Scheme environment GIMP provides is very primitive, e.g. without any reasonable error handling. Furthermore, must users are not familiar with Scheme as a language. Some users may therefore prefer to write scripts for the GIMP in Perl.

Perl as a language is probably more familiar to web-literate users as it is the major language for writing CGI scripts. Now, GIMP scripts may also be written with Perl. This tutorial will describe how to write such plug-ins and scripts for GIMP.

As there are several excellent tutorial texts describing the Perl language, this tutorial will assume a working knowledge of Perl, and will instead concentrate on the use of GIMP together with the use of the Perl modules Gimp and Gimp::Fu, written by Marc Lehmann

NOTE: This tutorial was originally written for a 1.2 version of GIMP. It was proofread and some updates were applied as of March 22, 2007. However, the sample scripts which are shown on this page have not been re-tested to verify that they will work with the current 2.2 version of GIMP.

1. What You Need

The Perl::Gimp tutorial scripts have been tested with the following versions:

  1. GIMP version 1.2 or later, with all its prerequisites.
  2. Perl version 5.005 or later.
  3. The Perl module Gtk, version 0.7003
  4. The Gimp module, version 1.201 or later

Perl and all its associated modules are available in source form from the Perl Comprehensive Archive Network, CPAN. It is also possible to download them in RPM format from the website.

2. The Gimp module

Most scripts make use of the simplified interface Gimp::Fu provides with the GIMP module. Gimp::Fu provides a framework for entering parameters to the script in a frame like interface, just like Script-Fu, but also allows running of the script in batch mode from the command line. This tutorial will go into a detailed description of the construction of a Gimp::Fu script but, before we do this, here is the general framework of a Perl-Fu script.

  use Gimp ":auto"; 
  use Gimp::Fu;
  # Register extension to GIMP
  register ... ;
  exit main();  # Handle over control to GIMP 

The interesting items to note in the script are the use of the two modules Gimp and Gimp::Fu, the register function (which will be described in detail below), and the way control is handed over to the Gimp module on line 6. The use of the ":auto" statement makes Perl automatically include all of the GIMP PDB functions and constants into the Perl name space.


Before going into the details of the Perl-Fu script, we will describe how to access the various functions of GIMP. All functions known to GIMP are available through the procedural database (PDB). All the PDB functions may be called from Perl, as will be seen below. These PDB functions are either internal to GIMP, or have been made available through a plug-in or a script extension. As far as the caller is concerned there is no difference. As we will see below, when a Perl function is registered through the register function it will appear in the PDB as well.

GIMP/Perl comes with a PDB browser available in Xtns -> PDB Explorer. (There is another PDB browser available in Xtns -> DB Browser but the PDB Explorer is more suited for Perl users.) This browser provides a way of seeing all the functions in the PDB, as well as their input and output parameters. E.g. the PDB Explorer entry for gimp_image_new, which will be used in the example below looks like this:

Blurb:Creates a new image with the specified width, height, and type.
In:INT32widthThe width of the image
INT32heightThe height of the image
INT32typeThe type of image { RGB (0), GRAY (1), INDEXED (2) }
Out:IMAGEimageThe ID of the newly created image
Help:Creates a new image, undisplayed with the specified extents and type. A layer should be created and added before this image is displayed, or subsequent calls to 'gimp_display_new' with this image as an argument will fail. Layers can be created using the 'gimp_layer_new' command. They can be added to an image using the 'gimp_image_add_layer' command

All the the constants mentioned in the PDB Explorer have been defined within Gimp::Fu and may be used within Perl. E.g. a call to create a new image of size 100x150 of type RGB looks as follows:

$img = gimp_image_new(100, 150, RGB)

The PDB entry above shows that gimp_image_new is called with three parameters (width, height, type). These are all of type INT32. This type, and other types, will be explained below.

Script-Fu scripts are called just like any other script according to the PDB signature in the PDB browser. E.g. to run the Script-Fu Basic One logo just do:

script_fu_basic1_logo("Hello", 72,

Unfortunately, as of this writing, calling Script-Fu from Perl has proved to make both Script-Fu and GIMP very unstable and caused both of them to crash. If any of the readers is able to describe what is needed to get it to run successfully, I will happily include this in a future version of this tutorial.

NOTE: When calling a PDB function from Perl::Gimp that has an image and a drawable as the two first arguments, only the drawable should be given as argument in the calling sequence.

4. Gimp::Fu and the register function

Gimp::Fu is Perl's answer to Script-Fu. It provides a simplified method for accepting parameters for a script through a Gtk interface, just like Script-Fu, but as we shall see below, it has some additional bells and whistles.

The main function for a Gimp::Fu script is the register function. This function declares the interface of the script to GIMP. The register function takes the following 10 parameters, that must all be provided:

  1. The name of the function - a string. This is the name of the function as it will be known in the PDB.
  2. A small description - a string
  3. A help text - a string
  4. The authors name - a string
  5. The copyright of the script - a string
  6. Creation date - a string
  7. Menu path - a string. The path has one of the two forms:
    1. "<Toolbox>/Xtns/Perl-Fu/Script Name"
    2. "<Image>/Perl-Fu/Script Name"
    If form 1. is given, then the script is a standalone script that appears in the menu hierarchy under Xtns/Perl-Fu and takes all of its inputs through the Gimp::Fu interface frame. If form 2. is given, on the other hand, the script is tied to the image menu popped up through use of the right-hand mouse button over any image. In this case Gimp::Fu will add, as the first two parameters to the script, the ID of the image and the drawable which was active when the script was invoked.
  8. The acceptable image types - a string. This list contains a list of image types acceptable. This field is only used for scripts that are in the "<Image>" hierarchy. For images in the <Toolbox> hierarchy, this should be an empty string. Possible values are listed in the table below:
    * Any images are accepted
    RGB RGB images
    RGBARGB images with alpha channels
    GREYGrey level images

  9. Parameters - A reference to an array of parameters. (A reference to an array in Perl is simply an array written within square brackets). Each parameter in turn is a reference to an array containing the following four or five values:
    1. The type of the parameter. The types recognized by Gimp::Fu and Perl are given in the following table:
      Type Possible forms Comment
      42 A number. PF_INT is a synonym to PF_INT32.
      3.141 A floating point number.
      A boolean value.
      An integer value through a slider and a spinner interface. The range parameter should be specified and is interpreted as minimum, maximum, and step, e.g. [0,100,1].
      PF_FONT -*-blippo-*-*-*-*-24-*-*-*-*-*-*-* A font in X11 font format. This interface launches a font browser.
      PF_STRING "A string" A string
      A color may either be expressed as a reference to an array of three components, or as a hexadecimal triple, proceeded by the hash sign.
      PF_TOGGLE 0
      A boolean toggle
      PF_IMAGE - An image
      PF_DRAWABLE - A drawable.
      PF_BRUSH A brush
      PF_GRADIENT A gradient
      PF_PATTERN A pattern

    2. The name of the parameter - a string
    3. A help text for the parameter
    4. Default value for the parameter. This should be given in the form listed in the table above.
    5. An array defining allowed range for the value. This is only possible for PF_SLIDER and PF_SPINNER.
  10. A reference to an array of return types of the sub in the 11th parameter.
  11. The sub to be called - a reference to a sub . This subroutine will be called with the associated menu entry declared through the Menu path described above. When the sub is called it is passed as arguments the list of parameters declared in field 9, described above, and in the case of a "<Image>..." script, the active image and layer as first and second parameters.
    A reference to a sub in Perl may be declared in two ways. You can declare a subroutine at a different place in the source file (e.g. sub run) and reference it by writing \&run. An alternative way is to write it inline by simply writing:
    sub { ($text, $color) = @_ ; ... }

    The sub is expected not need to display a new image after it has created it. Instead it is expected to return the new image or images that were created in accordance with the return types declared in parameter 10 of the register call described above. This behaviour has been added in order to be able to call the sub non-interactively. More about that behaviour below.

4.2 A commented script

The following Gimp::Fu script example shows the steps described in the previous section. It registers a script that takes two values, the size of the image and a color, and then produces an image of the requested size with the requested color. Quite useless but it shows the important steps of how to register a script, how to create a new image, and how to access some PDB functions.

  #!/usr/local/bin/perl -w
  use Gimp ":auto";
  use Gimp::Fu;
  sub img_uni {
      my ($size, $color) = @_;
      # Create a new image
      $img = gimp_image_new($size, $size, RGB);
      # Create a new layer
      $layer = gimp_layer_new($img, $size, $size, RGB,
                              "Layer 1", 100, NORMAL_MODE);
      # add the layer to the image
      gimp_image_add_layer($img, $layer, -1);
      # Set the background to the required color
      # Paint the layer
      gimp_edit_fill($layer, BG_IMAGE_FILL);
      # Return the image
      return $img;
        "img_uni",                 # fill in name
        "Create a uniform image",  # a small description
        "A tutorial script",       # a help text
        "Dov Grobgeld",            # Your name
        "Dov Grobgeld (c)",        # Your copyright
        "1999-05-14",              # Date
        "<Toolbox>/Xtns/Perl-Fu/Tutorial/Img Uni",   # menu path
         [PF_INT,   "size", "Img size", 100],
         [PF_COLOR, "color", "Img color", [255,127,0]] 
  exit main();

Most of these commands are directly copied out the PDB.

This script shows the essential steps of producing a stand-alone script:

10 Creating a new image.
13-14 Creating one or more layers.
17 Attaching the layer to the image.
19-23 Do some painting operations in the layers.
26 Return the image to the caller
29-42 Registration of the extension

To test the script, save it in the directory $HOME/.gimp-2.2/plug-ins. It must then be made executable through the command:

chmod +x $HOME/.gimp-2.2/plug-ins/uni

Then start GIMP. It is generally a good idea to test the syntax of the script with perl -c before starting GIMP. (A more official way to add scripts is to use the gimptool --install-bin command).

Note: It is not possible to add scripts once GIMP is running. On the other hand, it is possible to change a script which has already been registered, as long as the parameters don't change.

The script is now accessible through the menu system through the Xtns top menu.

When choosing this menu entry the following screen is popped up.

Choosing the default values creates a result like the image above.

5. Object oriented syntax

Gimp::Fu provides an alternative object-oriented syntax for the image and the drawable commands. Here is a table showing the procedural vs the object oriented syntax for a few commands:

procedural syntax object oriented syntax
gimp_image_add_layer($drw,-1); $img->add_layer($drw, -1);
gimp_drawable_width($drw); $drw->width();

The substitution rule for converting a PDB function call into a method is as simple as erasing ``gimp_image_'' from the beginning of the function call and calling this method through the image object. Similarly for the gimp_drawable_... functions.

Note that the object oriented syntax is only syntactic sugar that makes the calling syntax cleaner in some cases. The error messages are still given in the procedural format.

6. Painting areas with selections

In the uni script the function gimp_edit_fill was called to fill the whole image. Looking at the info for gimp_edit_fill in the PDB browser we find the following:

Blurb:Fill selected area of drawable
In: DRAWABLE drawable The drawable to fill from
INT32fill_type The type of fill: FG_IMAGE_FILL (0), BG_IMAGE_FILL (1), WHITE_IMAGE_FILL (2), TRANS_IMAGE_FILL (3), NO_IMAGE_FILL (4)
Help: This procedure fills the specified drawable with the fill mode. If the fill mode is foreground, the current foreground color is used. If the fill mode is background, the current background color is used. Other fill modes should not be used. This procedure only affects regions within a selection if there is a selection active.

Thus, if a selection is active when gimp_edit_fill is called only the selection is painted. There are lots of ways of choosing a selection as can be seen when searching for a ``select'' in the PDB. The example below uses gimp_rect_select, whose entry in the PDB looks as follows:

Blurb:Create a rectangular selection over the specified image
In:IMAGEimageThe image
FLOATxx coordinate of upper-left corner of rectangle
FLOATyy coordinate of upper-left corner of rectangle
FLOATwidththe width of the rectangle: width > 0
FLOATheightthe height of the rectangle: width > 0
INT32operationthe selection operation: {ADD (0), SUB(1), REPLACE (2), INTERSECT (3) }
INT32featherfeather option for selections
FLOATfeather_radiusradius for feather operation
Help: This tool creates a rectangular selection over the specified image. The rectangular region can be either added to, subtracted from, or replace the contents of the previous selection mask. If the feather option is enabled, the resulting selection is blurred before combining. The blur is a gaussian blur with the specified feather radius.

A simple use of this function which selects a rectangle in the middle of an image and paints that rectangle with a user defined color. This example also introduces a couple of new features we haven't seen before:

#!/usr/local/bin/perl -w
use Gimp ":auto";
use Gimp::Fu;
    "Paints the selection", "Paints the selection",
    "Dov Grobgeld", "Dov Grobgeld", "1999-05-14",
    "<Image>/Perl-Fu/Tutorial/Paint Select",
     [PF_COLOR, "color", "Rectangle color", [0,0,255]] ],
    sub {
        my($img, $layer, $color) = @_;
        my($width, $height) = (gimp_image_width($img),
        # Select a rectangle inside the image and paint it with color
                         $width/4, $height/4, $width/2, $height/2,
                         REPLACE, 0,0);
        gimp_edit_fill($layer, BG_IMAGE_FILL);
   # Tell GIMP not to display a new image
   return ();
exit main();

The result when run on our previous image.

6.1 Complex selections

Besides rectangular selections elliptical selections may also be created through the PDB functions gimp_ellipse_select() and gimp_free_select() which allows the selection of ellipses and polygons.

More complex selections may be created through the channel mechanism. The PDB gimp_channel_new() creates a new channel. The channel is a drawable that may be painted into, just like any other drawable, but with the difference that it is always a grey level image. Once the channel is finished, the channel may be loaded into the selection through the PDB function gimp_selection_load().

Search for ``select'' in the DB Browser to see a list of all the selection related functions.

6.2 Loops

In Perl it is trivial to write loops that, together with the various selecton tools, give powerful creative possibilities. Here is an example that mixes colors in circles. There is nothing really new here, but it shows the power of what we have described above.

use Gimp ":auto";
use Gimp::Fu;
sub circles {
    my ($size, $bgcolor, $radius) = @_;
    # Create the background
    $img = gimp_image_new($size, $size, RGB);
    $layer = gimp_layer_new($img, $size, $size, RGB,
                            "Layer 1", 100, NORMAL_MODE);
    gimp_image_add_layer($layer, -1);
    gimp_edit_fill($layer, BG_IMAGE_FILL);
    my $ncircles = int($size/$radius/2);
    for ($i=0; $i<$ncircles; $i++) {
        for ($j=0; $j<$ncircles; $j++) {
            # Be creative and mix colors
            $color = [$i*30, ($ncircles-$j)*25, ($i+$j)*15];
            # Select a circle
                                $i*$radius*2, $j*$radius*2,
                                $radius*2, $radius*2,
                                REPLACE, 1, 0, 0);
            # Paint the color in the circle
            gimp_edit_fill($layer, BG_IMAGE_FILL);
    return $img;
# register the script
register "circles", "a loop", "a loop", "Dov", "Dov", "1999-05-14",
     [PF_INT32, "size", "Img size", 100],
     [PF_COLOR, "bg", "Background color", [40,180,60]],
     [PF_INT32, "radius", "Circle radius", 10]
exit main();

The result.

7. Creating text, Hello World - writing text in an image

To create text the PDB function gimp_text_fontname() may be used. In this function the font is specified in the X11 font conventions. (There are also some older functions, gimp_text and gimp_text_ext in which the different X11 fields are specified explicitly.) Here is an example of a script that creates an image containing "Hello world".

use Gimp ":auto";
use Gimp::Fu;
sub text1 {
    my($font, $text) = @_;
    # Create a new image
    $img = gimp_image_new(350, 100, RGB);
    # Create a new layer and draw it to the image at the top
    $drw = gimp_layer_new($img, $img->width, $img->height,
                    RGB, "BG", 100, NORMAL_MODE);
    gimp_edit_fill($drw, BG_IMAGE_FILL);
    # Choose color of text
    # Create the text
    my $border = 10;
    my $text_layer = gimp_text_fontname($drw,  0, 0, $text,
                                  $border, 1,
                                  xlfd_size($font), $font);
    return $img;
# register the script
register "hello_world1", "basic text", "basic text", "Dov", "Dov",
    "<Toolbox>/Xtns/Perl-Fu/Tutorial/Basic text 1",
     [PF_FONT, "font", "font", "-*-utopia-bold-r-*-*-70-*-*-*-*-*-*-*"],
     [PF_STRING, "text", "text", "Hello world!"]
# Handle over control to GIMP
exit main();

The result above:

The script makes use of the function xlfd_size which extracts the size of the font from the X11 font name. This is necessary as the authors of gimp_text_fontname decided that the font size within the fontname is ignored.

One thing to note in this script is that the text that is created on line 24 is a floating layer, than needs to be anchored to its parent layer. This is done in line 27 through the call to gimp_floating_sel_anchor().

This script suffers from the problem that the image size is unrelated to the text size. This is taken care of in the following more complex example which shows the basic steps for a logo generating script.

The result is an image composed of two layers; a transparent text layer on top of a uniform background.

use Gimp ":auto";
use Gimp::Fu;
sub basic_logo {
    my($font, $border, $text, $bgcolor, $fgcolor) = @_;
    # Create a new image of an arbitrary size with
    $img = gimp_image_new(100, 100, RGB);
    # Create a new layer for the background of arbitrary size, and
    # add it to the image
    my $background = gimp_layer_new($img, 100, 100,
                              RGB, "Background", 100,
    gimp_image_add_layer($background, 1);
    # Choose color of text
    # Create the text layer. Using -1 as the drawable creates a new layer.
    my $text_layer = gimp_text_fontname($img, -1, 0, 0, $text,
                                  $border, 1,
                                  xlfd_size($font), $font);
    # Get size of the text drawable and resize the image and the
    # background layer to this size.
    my($width, $height) = ($text_layer->width, $text_layer->height);
    gimp_image_resize($img, $width, $height, 0, 0);
    gimp_layer_resize($background, $width, $height, 0, 0);
    # Fill the background layer now when it has the right size.
    gimp_edit_fill($background, BG_IMAGE_FILL);
    return $img;
# register the script
register "basic_logo", "basic logo", "basic logo",
    "Dov Grobgeld", "Dov Grobgeld",
    "<Toolbox>/Xtns/Perl-Fu/Tutorial/Basic Logo",
     [PF_FONT,   "font",     "font",   "-*-utopia-bold-r-*-*-70-*-*-*-*-*-*-*"],
     [PF_INT,    "border",   "border", "10"],
     [PF_STRING, "text",     "text", "Hello world!"],
     [PF_COLOR,  "bg_color", "Background color", [40,180,160]],
     [PF_COLOR,  "fg_color", "Background color", [255,255,0]],
# Handle over control to GIMP
exit main();

Note the special syntax of gimp_image_text_fontname() in line 23 in basic-logo with an image specified for a first parameter, and the drawable = -1. This is in contradiction to the rule above that the image should not be specified for PDB functions that take both an image and a drawable as the first two parameters. But since the drawable=-1, which has no image related to it, an image explicitly be provided. The special case drawable=-1 means that instead of creating a floating layer, a new image layer will be created.

The result shown in the dialog and the resulting image above.

8. Floating selections

When a region has been selected through one of the selection routines, the area outlined by the selection may be copied to the cut-buffer through the gimp_edit_copy command. The cut-buffer may subsequently be pasted into a different layer through the gimp_edit_paste command. When a layer is pasted it becomes a floating selection. This floating selection may be moved to its required position by the command gimp_layer_set_offsets, and finally it is pasted by the gimp_floating_sel_anchor command. Another way of determining the position of a pasted layer is to create a selection in the target image before the cut-buffer is pasted.

This is illustrated in the following program, which works on one image and takes as a parameter an another image, which it concatenates to the right of the first image. The lines 28-38 shows how the second image is copied and glued into the first image.

use Gimp qw( :auto );
use Gimp::Fu;
sub horiz_cat {
    my($img1, $drw1, $drw2) = @_;
    # Get image 2
    $img1 = $drw1->image();
    my $img2 = gimp_drawable_image($drw2);
    # Get sizes through OO syntax
    my($w1, $h1) = ($drw1->width, $drw1->height);
    my($w2, $h2) = ($drw2->width, $drw2->height);
    # The new height is the maximum height of the images
    my $hmax = $h1 > $h2 ? $h1 : $h2;
    # Create an undo group
    # Resize the drawable layer to make room for the img
    gimp_image_resize($img1, $w1+$w2, $hmax, 0, ($hmax-$h1)/2);
    gimp_layer_resize($drw1, $w1+$w2, $hmax, 0, ($hmax-$h1)/2);
    # Copy $drawable2 and paste it into the new space of $drawable1
    # select all of img2
    # copy it to the clipboard
    # make a selection in img 1 in the position where it is to be pasted
    gimp_rect_select($img1, $w1, ($hmax-$h2)/2, $w2, $h2, 0,0,0);
    # paste and then anchor it
    my $floating_layer = gimp_edit_paste($drw1, 0);
    # Close the undo group
    # Update the display
    return undef;
# register the script
register "horiz_cat", "Horizontal concat", "Horizontal Concat",
    "Dov Grobgeld", "Dov Grobgeld",
    "<Image>/Perl-Fu/Tutorial/Horizontal Concat",
     [PF_DRAWABLE,   "drawable",     "Drawable to concatenate",   undef],
# Handle over control to GIMP
exit main();

9. The Perl Server and stand-alone scripts

So far the scripts have all been started from the menu structure within GIMP. But there is another possibility and that is to run the scripts from the command line as a normal Perl program. When run this way the script tries to connect to the Perl-Server, and if it fails, it will launch GIMP on its own. If you plan to run several scripts this way, it is obviously much faster to run the Perl-Server since launching GIMP takes quite a bit of time. The Perl-server may be started from the Xtns menu.

When a Perl-Fu script is run from the command line, the result is the same as when it is run through the menus, except that it may be run with the --output (or -o) parameter in which case it will save the result to a file instead of displaying it within GIMP. This is great for batch creation of logos, etc.

The filename for the --output has some special magic that allows to set some special image saving parameters, like interlace, quality factor, etc. See the Gimp::Fu man page for details. Note that the normal rules about image and file types are still valid, thus, for example, in order to save an image as a gif file, it must be converted from RGB to an indexed image. Currently this functionality must be included in each script, but it is possible that a future version of Gimp::Fu, will include this conversion as an option.

Here are two invocations of the scripts declared above, but with output written to a jpg file and a png file. As we said above, we can't save them as gif as the scripts do not index the images.


uni -o /tmp/uni.ppm -size 100 -color "#5050ff"
basic-logo -font '-*-utopia-*-r-*-*-100-*-*-*-*-*-*-*' -o /tmp/bl.ppm -text "Perl rules"

Note: that due to a bug in my version of GIMP/Perl I was not able to output images in any format but in ppm and gif. Your mileage may vary. Another important use of this interface is that it enables running of the Perl debugger on the Perl-Fu scripts.

Note:The image is saved to the directory where GIMP was started from and not to the directory in which the scripts were invoked, unless a complete path is given!

10. End notes

This tutorial has covered only a small part of the possibilities available to a script writer. In particular the following issues available to Gimp::Perl scripts have not been covered:

The original tutorial can be found here and an updated version for GIMP 2.0 can be found here.

Tutorial © 1999-2002 Dov Grobgeld