ImageMagick Rounded Rectangles

There are many ways to create rounded rectangles with ImageMagick and PHP. After much thought, trial, and error, this is the solution I like best.

The basic approach is to define an image, then use the ratio of height to width, with some tweaking, to determine the rounding coordinates. Rounding is achieved using four arcs, with a strokewidth that is wide enough to cover the corner. Each arc is 90 degrees. After the arcs are drawn, the image is flattened and the stroke color is defined as transparent.

Command

convert -size ‘250x250′ xc:"#5f7172″ \
-stroke “#ffffff” -strokewidth 25 \
-fill none -draw ‘arc -13,51 51,-13 180,270′ \
-fill none -draw ‘arc -13,199 51,263 90,180′ \
-fill none -draw ‘arc 199,199 263,263 0,90′ \
-fill none -draw ‘arc 199,51 263,-13 270,360′ \
-flatten -transparent “#ffffff” -blur 0x0.1 -quality 100 \
tmp/r1.png

Image

Rounded rectangle

The rounded rectangle generator (above link), has been updated to use this approach.

Notes on rounded rectangles

  • Masking tended to remove the anti-aliasing, leaving the ‘corners’ a little rough or stepped.
  • Adding a background color to the tool allows ImageMagick to do a nicer job with the anti-aliasing.
  • Drawing arcs, instead of rounded rectangles seemed to work better. It was difficult to use the rounded rectangle to remove the corners.