Gravatar icons can be used on all websites that lets users write comments. It could be in a forum or on a blog. The image is retrieved from the Gravatar website and is based on the e-mail address of the person that makes the comment.

It is very easy to set up because it is just a normal image where the src attribute point to the Gravatar website. Here is a method that writes out such an image. It takes an e-mail address and a size. The default size used by Gravatar is 80 (80x80 pixels), but you can specify a smaller size if you’d like.

protected string Gravatar(string email, int size)
{
  System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  byte[] result = md5.ComputeHash(Encoding.ASCII.GetBytes(email));

  System.Text.StringBuilder hash = new System.Text.StringBuilder();
  for (int i = 0; i < result.Length; i++)
    hash.Append(result[i].ToString("x2"));

  System.Text.StringBuilder image = new System.Text.StringBuilder();
  image.Append("<img src=\"");
  image.Append("http://www.gravatar.com/avatar.php?");
  image.Append("gravatar_id=" + hash.ToString());
  image.Append("&amp;rating=G");
  image.Append("&amp;size=" + size);
  image.Append("&amp;default=");
  image.Append(Server.UrlEncode("http://example.com/noavatar.gif"));
  image.Append("\" alt=\"\" />");
  return image.ToString();
}

On the webpage you could then write out the Gravatar image like so:

<%=Gravatar("post@example.com", 60)%>

Comments


Comments are closed