create an image with a string randomly placed around the center

I'm trying to create an bunch of images that are very simple, just a string on a white background.

I would like the string to be located at a random position in the image, around the center and so that the whole string is visible (i.e. none hidden outside the image limits).

The strings are generated automatically, so I don't know their length beforehand, I just know they will be within a given range of lengths (6 - 15 chars).

For this I'm working with imagemagick's convert, and this is what I got atm:

convert -background "#ffffff" -size 800x480 -fill "#000000" -pointsize 72 -gravity Forget label:'mytext' output.png

which renders this: rendered image

gravity seems to influence the location of the label, but there's no random option for it.


Updated answer

Ok, I think you can draw the text and trim it to within an inch of its life, then pad it with 50px of white all around and place that randomly on your final canvas:

#!/bin/bash

bd=50   # 50px white space around letters
ps=72   # pointsize of letters
fh=480  # final height
fw=800  # final width
tmp="/tmp/$$.mpc" # temporary file

# Generate the text with padding all round so it can't touch edges and get its size
read w h < <(magick -pointsize $ps label:"$1" -trim -bordercolor white -border $bd -write "$tmp" -format "%w %h" info:)
echo "DEBUG: Text requires ${w}x${h} px"

# Work out random x,y offset from top-left where to place text
((x=RANDOM%(fw-w)))
((y=RANDOM%(fh-h)))

magick -size ${fw}x${fh} xc:white "$tmp" -geometry "+${x}+${y}" -composite result.png

Then you would save that as doit and make it executable with:

chmod +x doit

Then call it with:

./doit "Your text"
DEBUG: Text requires 381x153 px

result.png

enter image description here

Here's an animation of 100 frames:

enter image description here

Original Answer

Here's a basic template that draws your text at offset +50+20 from the centre in your image:

magick -size 640x480 xc:white -fill black -pointsize 72 -gravity center -annotate +50+20  "My Text" result.png

enter image description here


You can then randomize the +X+Y coordinates (also using -X-Y if you want the position offset above and to left of the centre-point instead of below and right) using your shell. Something like this:

for ((i=0;i<20;i++)) ; do 
  ((X=RANDOM%80))
  ((Y=RANDOM%80)) 
  magick -size 640x480 xc:white -fill black -pointsize 72 -gravity center -annotate +${X}+${Y}  "My Text" miff:- 
done | magick -delay 80 miff:- animated.gif

enter image description here


In Mark Setchell's answer, one can also use the ImageMagick internal fx:rand() operation to do the random offsets. The rand() function returns a value between 0 and 1.

magick -size ${fw}x${fh} xc:white "$tmp" -geometry "+%[fx:($fw-$w)*rand()]+%[fx:($fh-$h)*rand()]" -composite result.png