How to Auto Wrap Text to Width in ImageMagick?

When automating image generation, fitting long strings of text into a specific bounding box can be a challenge. The convert command in ImageMagick offers a built-in solution to this problem through the use of the caption: protocol instead of the standard -annotate or label: options. By defining a specific width and passing your text through caption:, ImageMagick automatically calculates the font size or wraps the text across multiple lines to perfectly fit your designated dimensions.

Step-by-Step Implementation

To make text wrap automatically, you need to set the width of your target canvas and use caption: to input your string. ImageMagick will handle the line breaks for you.

Here is the standard command structure:

magick convert -background white -fill black -font Arial -size 500x \
caption:"This is a long string of text that will automatically wrap once it hits the five hundred pixel boundary." \
output.png

Key Components Explained

Overlaying Wrapped Text on an Existing Image

If you want to add wrapped text on top of an existing image rather than creating a new one from scratch, you can combine the caption: protocol with the -composite operator.

magick convert background.jpg -size 400x -background none -fill white \
caption:"This wrapped text will overlay nicely on top of the background image." \
-geometry +50+100 -composite final_image.jpg

In this variation, -background none ensures the text box has a transparent background, and -geometry +50+100 positions the wrapped text 50 pixels from the left and 100 pixels from the top of the base image.