Question
In a web app, how can I display the user profile picture automatically?
I see that on some websites, after the sign-up, you get your profile picture automatically.
You don’t need to upload it.
It can be a personal profile picture or a random, colored pattern.
How can I achieve that in my web app?
Answer
If you have a web app where users sign up with their email, then you can easily get their profile picture too, without asking them to upload it.
Basically you can get a profile picture associated to their email address using a (free) service called Gravatar.
Here’s a Ruby code to obtain the Gravatar for a user:
def gravatar
hash = Digest::MD5.hexdigest email.downcase
"https://www.gravatar.com/avatar/#{hash}?default=identicon"
end
Basically you need to convert the email to lowercase, calculate the MD5 hash and output it in hexadecimal. Then you include it in the URL as a param. That URL will return an image for that user and you can use the URL directly as a src
in an img
tag.
For example in Rails views you can use:
<%= image_tag current_user.gravatar %>
Additionally there are many other params that you can include in the URL to change the default image, the size of the image and other options.
And if you want to have a rounded profile picture you can simply use CSS:
img.gravatar {
border-radius: 9999px;
}