Click here to Skip to main content
Licence CPOL
First Posted 19 Feb 2012
Views 9,883
Bookmarked 5 times

Gravatar avatars in C# for .NET

By | 19 Feb 2012 | Technical Blog
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.
A Technical Blog article. View original blog here.[^]

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:

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

That will render an:

<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 

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)

About the Author

qenn

Engineer

United States United States

Member

Follow on Twitter Follow on Twitter


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberMarc Brooks8:55 20 Feb '12  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Beta | 2.5.120516.1 | Last Updated 19 Feb 2012
Article Copyright 2012 by qenn
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid