Producing a VSCode-style code screenshot for Twitter with ImageMagick

Table of Contents

The Goal

The Trouble with Image Magick

I am new to Image Magick but am trying to get it to convert my image to a size and background pleasant for Twitter. The qualities I’m going for are as follows1:

  • my overall canvas size 16:9, so about 1200x675

  • my actual screenshot centered and about 3/4 the width

  • background texture of my choosing

    My early attempts were like the following, but it didn’t seem to actually do anything:

convert ds.png -adaptive-resize 1200 -size 1200x675 -texture ~/Pictures/DoctorWho/horizon.jpg -gravity Center ds.png

Solution

The answer took some help from a great SO answer2, along with some decrypting of the documentation an how to specify a geometry string. The answer demonstrated the use of parenthesis to group sections of specification to the complex ImageMagick API. And then I discovered the frame3 options and grokked the color syntax to add a nice little border.

convert \( ~/Pictures/DoctorWho/horizon.jpg -resize 1200x675 \) \( destructuring.png -resize 1000 -mattecolor '#003b6f' -frame 5 \) -gravity center -compose over -composite ds.png

It was that second resize arg, after destructuring.png, that took some reworking, via the ImageMagick geometry docs.4

Footnotes

1 These are per Adobe’s reading of Twitter’s 2021 desired dimensions. https://www.adobe.com/express/discover/sizes/twitter

2 Some of the magick syntax was shared here: https://stackoverflow.com/questions/69638430/how-to-use-imagemagick-to-give-background-and-dimensions-to-my-screenshot

3 Frames in ImageMagick, a bit more functional than border. http://www.imagemagick.org/script/command-line-options.php#frame

4 These were partially literal and partially variable, resulting in something that is in no way copy-pasteable. Where it says “xheight” it means, for example, x200 for a height of 200 but with a literal char x. http://www.imagemagick.org/script/command-line-processing.php#geometry

Tory Anderson avatar
Tory Anderson
Web App Engineer, Digital Humanist, Researcher, Computer Psychologist