5

I am working on Elixir and looking to make an avatar service. If the user doesn't have an avatar, want to make one with their initials on it, like so:

enter image description here

I really haven't the slightest idea where to start or how to do this.

IgorekPotworek
  • 1,317
  • 13
  • 33
brandonhilkert
  • 4,205
  • 5
  • 25
  • 38

2 Answers2

6

You can use ImageMagick to do this. Simply call the convert command via System.cmd and pass the options to it. Here's a simple example how to generate an image similar to the one you posted. I'll leave the fine-tuning up to you.

def generate(outfile, initials) do
  size = 512
  resolution = 72
  sampling_factor = 3
  System.cmd "convert", [
    "-density", "#{resolution * sampling_factor}",                # sample up
    "-size", "#{size*sampling_factor}x#{size*sampling_factor}",   # corrected size
    "canvas:#E0E0E0",                                             # background color
    "-fill", "#6D6D6D",                                           # text color
    "-font", "/Library/Fonts/Roboto-Bold.ttf",                    # font location
    "-pointsize", "300",                                          # font size
    "-gravity", "center",                                         # center text
    "-annotate", "+0+#{25 * sampling_factor}", initials,          # render text, move down a bit
    "-resample", "#{resolution}",                                 # sample down to reduce aliasing
    outfile
  ]
end

For example this

generate('out.png', 'JD')

will generate the following image:

enter image description here

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • Not working with initials like "WW". Without the pointsize imagemagick tries to calculate the best fitting pointsize. But I found out, that ImageMagick is making strange stuff. If you have something like "MR" the gravity center is not working correct. After a -trim it removes a part of the right side of the "R". – Sardoan Oct 17 '17 at 17:39
4

Use Mogrify. It is a Elixir-ImageMagick integration.

Raj
  • 22,346
  • 14
  • 99
  • 142