Generate images with name initials using Elixir and ImageMagick.
When a new user signs up to your website, you may want to generate an initial profile picture for them using their initials.
Here’s a nice way to do it using Elixir, ImageMagick, and a custom font.
First make sure you have ImageMagick installed. On Mac, it’s pretty easy to just use Homebrew.
brew install imagemagick
Here’s where the magick (kek) happens.
@doc """
Generates an image using first name and last name of a user using imagemagick's convert command line tool.
"""
@spec create_from_initials(binary, binary) :: {:ok, binary}
def create_from_initials(first_name, last_name) when byte_size(first_name) > 0 and byte_size(last_name) > 0 do
size = 512
resolution = 72
sampling_factor = 3
background_color = "#003366"
text_color = "#FFFFFF"
initials = "#{String.at(first_name, 0)}#{String.at(last_name, 0)}"
image_path = System.tmp_dir!() |> Path.join("#{initials}.png") System.cmd("convert", [
# sample up
"-density",
"#{resolution * sampling_factor}",
# corrected size
"-size",
"#{size * sampling_factor}x#{size * sampling_factor}",
# background color
"canvas:#{background_color}",
# text color
"-fill",
text_color,
# font location
"-font",
Application.app_dir(:my_app, "priv/fonts/SourceSansPro-Regular.otf"),
# font size
"-pointsize",
"300",
# center text
"-gravity",
"center",
# render text in the center
"-annotate",
"+0+0",
"#{initials}",
# sample down to reduce aliasing
"-resample",
"#{resolution}",
image_path
])
{:ok, image_path}
end
Lots of ImageMagick flags, but they’re all commented for you to understand what each does.
Notice how I placed the custom font file in the priv
folder and created a folder called fonts.
Thanks to Patrick for his answer on StackOverflow, I took his initial code and added some tweaks to it to make it easier to configure.
Hope this helps you out! Leave a 👏if this saved you some time!