Skip to content

Instantly share code, notes, and snippets.

@trepmal
Created May 1, 2020 23:44
Show Gist options
  • Save trepmal/70ef6f3e2cbbe5acca84ea4c9c7ad9e5 to your computer and use it in GitHub Desktop.
Save trepmal/70ef6f3e2cbbe5acca84ea4c9c7ad9e5 to your computer and use it in GitHub Desktop.
#!/bin/bash
convert='/usr/local/bin/convert'
# flight check: must have imagemagick
if [ ! $(which $convert) ]; then
echo 'Error: `convert` required'
exit;
fi;
# flight check: must pass arg
if [ $# -eq 0 ]; then
echo "Usage:"
echo "bash ${0} <word>"
exit;
fi
while [ ! $# -eq 0 ]
do
case "$1" in
--help | -h)
echo "Usage:"
echo "${0} <filename>"
echo "--help | -h Show this"
echo "--debug Print some extra info"
echo "--circle Enlarge border radius"
exit;
;;
--debug)
shift
debug=true
;;
--circle)
shift
circle=true
;;
*)
word="$1"
shift
;;
esac
done
if [ -z "$word" ]; then
echo 'Error: input not valid'
exit;
fi;
wordescape="${word//[[:space:]]/-}"
wordimage="base-$wordescape.png"
wordoutput="$wordescape.png"
if [ ! -z $debug ]; then
echo "What are we making:"
echo 'word: ' "$word"
echo 'wordescape: ' "$wordescape"
echo 'wordimage: ' "$wordimage"
echo 'wordoutput: ' "$wordoutput"
echo
fi
fontpath=$HOME'/Library/Fonts/SourceSansPro-Bold.otf'
if [ -f $fontpath ]; then
fontparam="-font $fontpath";
else
fontparam=''
fi
# gen image
$convert -size 128x128 -gravity center -background white -fill black $fontparam label:"\ $word " $wordimage
# remove excess
$convert $wordimage -trim $wordimage
padding=10
# add uniform padding to ensure space for background
$convert $wordimage -bordercolor none -border $padding $wordimage
# extract dimensions
dims=$(convert $wordimage -print "%wx%h\n" /dev/null)
imgw="$(cut -d'x' -f1 <<<$dims)"
imgh="$(cut -d'x' -f2 <<<$dims)"
# calc new size
newimgw=$(expr $imgw + $padding) # we don't need to account for padding on both sides, we're just creating some buffer
newimgh=$(expr $imgh + $padding)
# top left corner from 0x0
topleftx=5
toplefty=5
# bottom right corner from 0x0
bottomrightx=$(expr $newimgw - $topleftx)
bottomrighty=$(expr $newimgh - $toplefty)
radius=10
if [ ! -z $circle ]; then
radius=$(expr $newimgw / 2)
fi
if [ ! -z $debug ]; then
echo "Image specs:"
echo 'trimmed w: ' $imgw
echo 'trimmed h: ' $imgh
echo 'new w: ' $newimgw
echo 'new h: ' $newimgh
echo 'topleftx: ' $topleftx
echo 'toplefty: ' $toplefty
echo 'bottomrightx: ' $bottomrightx
echo 'bottomrighty: ' $bottomrighty
echo 'radius: ' $radius
echo
fi
output="final-$word.png";
$convert -size "${newimgw}x${newimgh}" xc:none -fill white -gravity center \
-draw "roundrectangle ${topleftx},${toplefty} $bottomrightx,$bottomrighty ${radius},${radius}" \
-draw "image over 0,0 0,0 '$wordimage'" \
-resize '128x128>' $wordoutput
echo $wordoutput
# clean up
rm $wordimage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment