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

Screenshot 2020-05-23 at 01 49 08
Screenshot 2020-05-23 at 01 49 18
Screenshot 2020-05-23 at 01 49 29

@pedrocarmona
Copy link
Author

pedrocarmona commented Jun 2, 2020

Usage

app/services/user/default_avatar.rb

# frozen_string_literal: true

require "initials_avatar"

class User
  class DefaultAvatar
    class << self
      def attach(user)
        initials_avatar = InitialsAvatar.new(initials: user.name.initials)
        io = File.open(initials_avatar.avatar_path)

        user.avatar.attach(
          io: io, filename: 'avatar.png', content_type: 'image/png'
        )
      end
    end
  end
end

app/models/user.rb

class User < ApplicationRecord
  ...
  before_create :default_avatar
  ...
  has_person_name
  ...
  def default_avatar
    User::DefaultAvatar.attach(self) unless avatar.attached?
  end
end

@pedrocarmona
Copy link
Author

to test on circle ci add build step:

 - run:
          name: Install image utils and fonts
          command: |
            sudo apt-get update
            sudo apt-get install -y --no-install-recommends imagemagick libmagickcore-6.q16-3-extra gsfonts
   

@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