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.pngKey Components Explained
-size 500x: This is the most crucial part of the command. By specifying the width (500) but leaving the height blank (justx), you tell ImageMagick to fix the width and let the image grow vertically to fit all the wrapped text at the current font size.caption:"Your text here": Unlikelabel:, which shrinks text to fit on a single line,caption:actively looks for spaces in your string to break the text into new lines.- **
-fontand-pointsize**: You can explicitly set a-pointsize(e.g.,-pointsize 24). If you choose to specify a strict bounding box instead (like-size 500x300), ImageMagick will automatically scale the font size down so the wrapped text fits entirely within those exact dimensions.
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.jpgIn 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.