Skip to content

Instantly share code, notes, and snippets.

@pedrocarmona
Last active December 24, 2022 16:50
Show Gist options
  • Save pedrocarmona/79f8be1c473a5213923221067301d5b8 to your computer and use it in GitHub Desktop.
Save pedrocarmona/79f8be1c473a5213923221067301d5b8 to your computer and use it in GitHub Desktop.
Initials avatar - create an image with letters for using as the user avatar.
require "mini_magick"
# require "initials_avatar"
# InitialsAvatar.new(initials: "PC").avatar_path
class InitialsAvatar
BACKGROUND_COLORS = [
"#C53030", "#9C4221", "#975A16", "#2F855A", "#2C7A7B", "#2B6CB0", "#434190", "#553C9A", "#97266D"
]
def initialize(initials:)
@initials = initials
@background_color = BACKGROUND_COLORS.sample
create
end
def avatar_path
image.path
end
private
def image
@image ||= Tempfile.new(%W[mini_magick_ .png])
end
def create
MiniMagick::Tool::Convert.new do | new_image |
new_image.background "#{@background_color}"
new_image.pointsize '90'
new_image.font font
new_image.fill "#FFFFFF"
new_image.size '180x180'
new_image.gravity 'center'
new_image << "label:#{@initials}"
new_image << "png:#{image.path}"
end
end
def font
if `identify -list font | grep Helvetica`.empty?
"DejaVu-Sans"
else
"Helvetica"
end
end
end
@pedrocarmona
Copy link
Author

pedrocarmona commented Sep 6, 2021

mac os:
brew install imagemagick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment