Adding clippath information to an image

After posting the previous java based answer, I was wondering if it would be possible to script gimp in a way to do what we want. Turns out this is possible and quite easy!

First install the following gimp plugin wich loads the image, draws the path and then saves the image as tif. Copy it to your gimp plugins folder. On Mac this is ~/Library/Application Support/GIMP/2.10/plug-ins/addpath.py. Create the plug-ins folder if it doesn't exist yet. Also make sure the python file is executable by the user who runs gimp (chmod u+x addpath.py).

#!/usr/bin/env python

from gimpfu import pdb, main, register, PF_STRING

def add_path(infile, outfile):
    image = pdb.gimp_file_load(infile, 'image')
    vectors = pdb.gimp_vectors_new(image, 'clippath')
    w = image.width
    h = image.height
    path = [
        # The array of bezier points for the path.
        # You can modify this for your use-case.
        # This one draws a rectangle 10px from each side.
        # Format: control1-x, control1-y, center-x, center-y, control2-x, control2-y
        10, 10, 10, 10, 10, 10,
        w - 10, 10, w - 10, 10, w - 10, 10,
        w - 10, h - 10, w - 10, h - 10, w - 10, h - 10,
        10, h - 10, 10, h - 10, 10, h - 10
    ]
    pdb.gimp_vectors_stroke_new_from_points(vectors, 0, len(path), path, True)
    pdb.gimp_image_add_vectors(image, vectors, 0)
    drawable = pdb.gimp_image_get_active_layer(image)
    pdb.file_tiff_save(image, drawable, outfile, 'image.tif', 0)

args = [(PF_STRING, 'infile', 'GlobPattern', '*.*'), (PF_STRING, 'outfile', 'GlobPattern', '*.*')]
register('python-add-path', '', '', '', '', '', '', '', args, [], add_path)

main()

After that, you can start gimp without user interface in batch mode, executing the plugin.

gimp -i -b '(python-add-path RUN-NONINTERACTIVE "/absolute/path/to/your/input/file.png" "/absolute/path/to/the/tif/file.tif")' -b '(gimp-quit 0)'

Without the second -b '(gimp-quit 0)' gimp keeps running. You can also ask gimp to read the batch commands from stdin. That way it stays open and you can send new "add-path" commands to it simply by writing to stdin.

gimp -i -b -