Generate a favicon based on text in the command line

I love finding new ways to automate tasks, and one that I was tasked with doing recently involved making a favicon for a website. While generally this is considered to be something only possible in a GUI manually, I developed a way to achieve this by implementing a shell script in linux using ImageMagick.

The script

Now step into my shell script, which utilizes the convert functionality provided via the ImageMagick library.

I start out the script by using the boilerplate bash shell designation and added additional logic to determine if an argument was provided to the script. This argument will be the text string that will be used to create our icon:

#!/bin/bash

# Check if the text argument is provided
if [ -z "$1" ]; then
echo "Usage: $0 text"
exit 1
fi

I then set some variables to be used throughout the rest of the script. I capture the text argument fed into the shell script, set the font to be used, the size of the favicon, and the color of the text.

text="$1"
font="Hack-Regular"
size="32"
color="black"
background="transparent"

Then ImageMagick does its magic (no pun intended). It takes all of the variables defined earlier as parameters to the convert application. This will create the initial PNG file that will ultimately become the .ico we will use for our favicon.

touch test.png

convert -font $font -pointsize $size -fill $color -background $background label:"$text" test.png

Different size variants of this image are created and added to a single ICO file that becomes our favicon.ico. After a little bit of clean up, the script is done! A favicon is generated with the text and font style that were fed into the program and specified in this script configuration.

convert test.png -resize 16x16 favicon-16.png
convert test.png -resize 32x32 favicon-32.png

rm test.png

# Combine the resized PNG files into a single ICO file

convert favicon-16.png favicon-32.png -colors 256 favicon.ico  

# Delete the PNG files

rm favicon-16.png favicon-32.png

# Display a message

echo "Favicon created from text: $text"

So there you have it! No more opening up an image editor and clicking through menus if you are just looking to generate a clean favicon for your personal site or other project. This script could be modified to customize your font, background color, and more.

Questions, comments, or feedback? Feel free to email me.