Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Gravatar Avatars in C# for .NET

5.00/5 (2 votes)
19 Feb 2012CPOL 27.4K  
Gravatar Avatars in C# for .NET

The Gravatar API is deliciously simple. Just hash a person's email, and you've got that person's avatar.

There's a new project called NGravatar on Google Code that makes that process even easier for developers on .NET MVC. It provides simple extension methods for retrieving images from gravatar.com and specifying the size, maximum rating, etc.

A usage example might look like this:

ASP.NET
<%= 
    Html.Gravatar("ngravatar@kendoll.net", 220, null, NGravatar.Rating.PG, 
        new { style = "display:block;margin:0px auto;" })
%>

That will render an:

HTML
<img>

tag whose source is the Gravatar avatar for ngravatar@kendoll.net and whose other HTML attributes are defined as specified.

Below, you'll find the nuts and bolts of how the image URLs are created. For those using Visual Studio 2010, you can get started even quicker by installing the NGravatar package from NuGet:

PM> Install-Package NGravatar 

C#
using System;
using System.Collections.Generic;
 
namespace NGravatar
{
    /// <summary>
    /// NGravatar avatar rating.
    /// </summary>
    public enum Rating
    {
        /// <summary>
        /// G
        /// </summary>
        G,
        /// <summary>
        /// PG
        /// </summary>
        PG,
        /// <summary>
        /// R
        /// </summary>
        R,
        /// <summary>
        /// X
        /// </summary>
        X  
    }
 
    /// <summary>
    /// Object that renders Gravatar avatars.
    /// </summary>
    public class Gravatar
    {
        private static readonly int MinSize = 1;
        private static readonly int MaxSize = 512;
 
        private int _Size = 80;
        private Rating _MaxRating = Rating.PG;
 
        /// <summary>
        /// The default image to be shown if no Gravatar is found for an email address.
        /// </summary>
        public string DefaultImage { get; set; }
 
        /// <summary>
        /// The size, in pixels, of the Gravatar to render.
        /// </summary>
        public int Size            
        {
            get { return _Size; }
            set
            {
                if (value < MinSize || value > MaxSize)
                    throw new ArgumentOutOfRangeException("Size", 
            "The allowable range for 'Size' is '" + MinSize + 
            "' to '" + MaxSize + "', inclusive.");
                _Size = value;
            }
        }
 
        /// <summary>
        /// The maximum Gravatar rating allowed to display.
        /// </summary>
        public Rating MaxRating
        {
            get { return _MaxRating; }
            set { _MaxRating = value; }
        }
 
        /// <summary>
        /// Creates an img tag whose source is the address of the Gravatar 
        /// for the specified <paramref name="email"/>.
        /// </summary>
        /// <param name="email">The email address whose Gravatar should be rendered.
        /// </param>
        /// <returns>An HTML img tag of the rendered Gravatar.</returns>
        public string Render(string email)
        {
            return Render(email, null);  
        }
 
        /// <summary>
        /// Gets a link to the image file of the Gravatar for the specified 
        /// <paramref name="email"/>.
        /// </summary>
        /// <param name="email">The email whose Gravatar image source should be returned.
        /// </param>
        /// <returns>The URI of the Gravatar for the specified <paramref name="email"/>.
        /// </returns>
        public string GetImageSource(string email)
        {
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(email.Trim()))
                throw new ArgumentException("The email is empty.", "email");
 
            var imageUrl = "http://www.gravatar.com/avatar.php?";
            var encoder = new System.Text.UTF8Encoding();
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var hashedBytes = md5.ComputeHash(encoder.GetBytes(email.ToLower()));
            var sb = new System.Text.StringBuilder(hashedBytes.Length * 2);
 
            for (var i = 0; i < hashedBytes.Length; i++)
                sb.Append(hashedBytes[i].ToString("X2"));
 
            imageUrl += "gravatar_id=" + sb.ToString().ToLower();
            imageUrl += "&rating=" + MaxRating.ToString();
            imageUrl += "&size=" + Size.ToString();
 
            if (!string.IsNullOrEmpty(DefaultImage))
                imageUrl += "&default=" + System.Web.HttpUtility.UrlEncode(DefaultImage);
 
            return imageUrl;
        }
 
        /// <summary>
        /// Creates an img tag whose source is the address of the Gravatar 
        /// for the specified <paramref name="email"/>.
        /// </summary>
        /// <param name="email">The email address whose Gravatar should be rendered.
        /// </param>
        /// <param name="htmlAttributes">Additional attributes to include in the img tag.
        /// </param>
        /// <returns>An HTML img tag of the rendered Gravatar.</returns>
        public string Render(string email, IDictionary<string, string> htmlAttributes)
        {
            var imageUrl = GetImageSource(email);
 
            var attrs = "";
            if (htmlAttributes != null)
            {
                htmlAttributes.Remove("src");
                htmlAttributes.Remove("width");
                htmlAttributes.Remove("height");
                foreach (var kvp in htmlAttributes)
                    attrs += kvp.Key + "=\"" + kvp.Value + "\" ";  
            }
 
            var img = "<img " + attrs;
            img += "src=\"" + imageUrl + "\" ";
            img += "width=\"" + Size + "\" ";
            img += "height=\"" + Size + "\" ";
            img += "/>";
 
            return img;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)