home ~ projects ~ socials

Round The Corners Of An Image With ImageMagick

This is how I'm making PNG files that have rounded corners with a transparent background.

Single Color Rounded Border

cd image-magick/rounded-corners

magick input.jpg \
-format 'roundrectangle 0,0 %[fx:w+1],%[fx:h+1] 10,10' \
-write info:tmp.mvg \
-alpha set -bordercolor none -border 1 \
\( +clone -alpha transparent -background none \
-fill white -stroke none -strokewidth 0 -draw @tmp.mvg \) \
-compose DstIn -composite \
\( +clone -alpha transparent -background none \
-fill none -stroke black -strokewidth 1 -draw @tmp.mvg \) \
-compose Over -composite \
single-color-border.png

rm tmp.mvg

echo "done"
Output:
done

Multi-Color Rounded Border

cd image-magick/rounded-corners

magick input.jpg \
-format 'roundrectangle 1,1 %[fx:w+4],%[fx:h+4] 15,15' \
-write info:tmp.mvg \
-alpha set -bordercolor none -border 3 \
\( +clone -alpha transparent -background none \
-fill white -stroke none -strokewidth 0 -draw @tmp.mvg \) \
-compose DstIn -composite \
\( +clone -alpha transparent -background none \
-fill none -stroke black -strokewidth 3 -draw @tmp.mvg \
-fill none -stroke white -strokewidth 1 -draw @tmp.mvg \) \
-compose Over -composite \
multi-color-border.png

echo "done"
Output:
done

Here's how to run the command with python and all the necessary escaping changes:

from subprocess import run

input_path = "some-input.jpg"
output_path = "some-output.jpg"


run([
"/opt/homebrew/bin/magick", input_path, 
"-format",  "roundrectangle 0,0 %[fx:w+1],%[fx:h+1] 10,10",
"-write", "info:tmp.mvg", 
"-alpha", "set", "-bordercolor", "none", "-border", "1",
"(", "+clone", "-alpha", "transparent", "-background", "none",
"-fill", "white", "-stroke", "none", "-strokewidth", "0", "-draw", "@tmp.mvg", ")",
"-compose", "DstIn", "-composite",
"(", "+clone", "-alpha", "transparent", "-background", "none",
"-fill", "none", "-stroke", "#c7c7c7", "-strokewidth", "1", "-draw", "@tmp.mvg", ")",
"-compose", "Over", "-composite",
output_path])
-- end of line --

References