ImageMagick placeholder images

Published Apr 6, 2021

Recently, I’ve been building a website where I know the sizes of images but I don’t have the images themselves. This makes it difficult to create layouts because I’m still learning how new techniques (like CSS grids) affect content sizing. So I need placeholder images.

At first, I used a real raster image editor:

  1. Open up GIMP.
  2. Set the correct size canvas.
  3. Paint-bucket fill a vibrant color.
  4. Add vertically- and horizontally-centered text describing what this image should be replaced with.
  5. Export to PNG (somehow I can remember that it’s Ctrl+Shift+E but not where it is in the menus 😅).

Then I got really tired of all of that. While waiting for the site to build again, I asked if ImageMagick could do all of that for me. (Actually, it was more of a “how” than an “if” because it can do pretty any image manipulation I’ve ever asked of it.) And thanks to this forum post, we know that it can!

Here’s an annotated version of the snippet that’s now in my ZSH “aliases”:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
img-placeholder() {
    # The only required argument is the size in WxH form.  As an example, for
    # an image 100 pixels wide and 20 pixels tall, use '100x10'.
    local size="$1"

    # If there's a second argument, use it as the output file path.  Otherwise,
    # name the file to match its size.  For example, '100x10.png'.
    local outfile=''
    if [ "$#" -gt 1 ]; then
        outfile="$2"
    else
        outfile="${size}.png"
    fi

    # `magick` is ImageMagick, which can also be spelled `convert`.
    # `caption:"${size}"` adds text (something like "100x10").
    # `-gravity Center` causes later the text to anchor to the center of the
    # image.
    #
    # Order is important!  If you swap the order of the gravity and caption,
    # the text is upper-left aligned instead.
    magick \
      -size "${size}" \
      -background lime \
      -gravity Center \
      caption:"${size}" \
      "${outfile}"

    # Print the name of the output file so the generated image can be used in
    # shell pipelines.
    echo "${outfile}"
}

And a usage example with the generated images:

$ img-placeholder 233x144
233x144.png
$ img-placeholder 144x233 portrait.png
portrait.png
$ ls
233x144.png  portrait.png

233x144.png:

233x144.png

portrait.png:

portrait.png