Skip to content

GIMP Python scripting

GIMP has support for python scripts that can be used to operate over images, which can be useful to automate the batch execution of transformations over complex sets of layers or for operations you do frequently.

When GIMP is compiled with python scripting support (which should already be the default in full installs), an interactive python console will be available under the Filters -> Python-Fu submenu. You can then copy-paste snippets into the console to perform operations.

Executing print gimp.directory into the console should give you the path where the local GIMP configuration for the current user is located, in there you can find a plug-ins directory where you can place python scripts.

The full documentation for the gimp python modules can be found here: https://www.gimp.org/docs/python/

Sample scripts ​

Apply cartoon & pixelize filters to the first layer ​

python
img = gimp.image_list()[0]
pdb.gimp_image_undo_group_start(img)

layer = img.layers[0]
maskRadius = 20.0 # Cartoon mask radius (radius of pixel neighborhood).
blackPct = 0.001  # Percentage of darkened pixels to set to black (0.0 - 1.0).
paletteSize = 64  # Number of colors for the final palette
pixelSize = 5     # Size of the pixels
(img.base_type != 0) and pdb.gimp_convert_rgb(img) # cartoon requires RGB mode
pdb.plug_in_cartoon(img, layer, maskRadius, blackPct)
pdb.plug_in_pixelize(img, layer, pixelSize)
pdb.gimp_convert_indexed(img, 0, 0, paletteSize, 0, 1, "colors")

pdb.gimp_image_undo_group_end(img)

Iterate over the group layers & resize them to the image size ​

python
img = gimp.image_list()[0]
pdb.gimp_image_undo_group_start(img)

for layer in img.layers:
 if isinstance(layer, gimp.GroupLayer):
 print("+ group: " + layer.name)
  for l in layer.layers:
   print("  - layer: " + l.name)
   l.visible = True
   pdb.gimp_layer_resize_to_image_size(l)

pdb.gimp_image_undo_group_end(img)

Export all layers as images ​

python
import os

def export_layers(img, path, group=img):
  if not os.path.exists(path):
    os.makedirs(path)
  for layer in group.layers:
    if isinstance(layer, gimp.GroupLayer):
      print("+ group: " + layer.name)
      export_layers(img, os.path.join(path, layer.name), layer)
    else:
      layer.visible = True
      pdb.gimp_layer_resize_to_image_size(layer)
      filename = layer.name
      fullpath = os.path.join(path, filename + ".png")
      print("- exporting layer: " + filename)
      pdb.gimp_file_save(img, layer, fullpath, filename)

img = gimp.image_list()[0].duplicate()
export_layers(img, "/tmp/test")

Personal page