Search code examples
imagemagick

image-magic: automatically adding the filenames of the stacking images


My bash script uses convert and montage of the Image magic to stack 2xN multi-image chart. Convert:

convert  \( "${output}/type1*.png" -append \) \( "${output}/type2*.png" -append \) +append -background white -alpha deactivate ${output}/summary.png

Montage:

montage \( "${output}/type1*.png" \) \( "${output}/type2*.png" \) -geometry 800x600+1+1 -tile x2 -frame 4 -background white -mattecolor lightgoldenrod2 -mode Frame -bordercolor white ${output}/summary.png

Would it be possible via some option to automatically add the name of the stacked images directly on each initial png file?


Solution

  • Of course. I made 4 randomly coloured input images, each 100x100 like this:

    magick -size 2x2 xc: +noise random -crop 1x1 -scale 100x100 +repage type-%02d.png
    

    enter image description here

    They are named like this:

    -rw-r--r--@ 1 mark  staff  595 11 Oct 10:35 type-00.png
    -rw-r--r--@ 1 mark  staff  594 11 Oct 10:35 type-01.png
    -rw-r--r--@ 1 mark  staff  595 11 Oct 10:35 type-02.png
    -rw-r--r--@ 1 mark  staff  595 11 Oct 10:35 type-03.png
    

    The basic technique you need is to:

    • iterate over the input images
    • add a label to each one
    • aggregate and pipe all the resulting individual images into montage

    #!/bin/bash
    
    for f in type-*png; do             
      magick "$f" -gravity South -fill black -background Plum -font "/System/Library/Fonts/Supplemental/Comic Sans MS Bold.ttf" -splice 0x18 -annotate +0+2 "$f" miff:-
    done | magick montage -geometry +1+1 -tile x2 miff:- montage.png
    

    enter image description here


    Here's another example, but with an under-colour underneath the text and the text directly on the image and a transparent background to the montaged output:

    #!/bin/bash
    
    for f in type-*png; do             
      magick "$f" -fill white  -undercolor '#00000080' -gravity South -annotate +0+5 "$f" miff:-
    done | magick montage -background none -geometry +1+1 -tile x2 miff:- montage.png
    

    enter image description here

    Obviously you can diddle around with the colours, fonts, positioning as you wish, but the core technique remains the same.

    Note: MIFF: is just "Magick Image File Format", a format specific to ImageMagick that is guaranteed to maintain and pass on all aspects of its input - from bit-depth, through comments, through quality, through transparency down to EXIF data and beyond.

    Note: The annotation methods I have used are derived from the excellent work by Anthony Thyssen linked here and there are many, many other examples - well worth a read.