Some emails coming in wanting to know an easy way to get Gravatars into their .NET applications. I’ll show 2 ways, both in C# and VB.
First I’ll share with you my MD5 function used to return the hash of a string. In this case, the hash of a users email address.
Function MD5(ByVal strToHash As String) As String
Dim md5Obj As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
bytesToHash = md5Obj.ComputeHash(bytesToHash)
Dim strResult As String = ""
For Each b As Byte In bytesToHash
strResult += b.ToString("x2")
Next
Return strResult
End Function
Create a new windows forms application and add a single picturebox control. For test/example purpose, please the following code in your “Form1_Load” sub.
'Declare a constant here that is half of our URL
Const GURL = "http://www.gravatar.com/avatar/"
'GravatarSize ranges from 1-512
'Rating ranged from G, PG, R, X
'IconType ranges from monsterid, identicon, wavatar
Dim tmp As String = GURL & MD5(Email) & "?s=" & GravatarSize & "&r=" & Rating & "&d=" & IconType
'Now lets use the picturebox "ImageLocation" method to load the Image.
picGravatar.ImageLocation = tmp
An example would be:
Dim tmp As String = GURL & MD5(dremation@gmail.com) & "?s=60&r=g&d=monsterid"
The result would be

Now, for the C# example. Although C# and VB are very close in syntext I will include this example as well.
First, here is the MD5 function.
private string MD5(string Email)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.ASCII.GetBytes(Email);
data = x.ComputeHash(data);
string ret = "";
for (int i = 0; i < data.Length; i++)
ret += data[i].ToString("x2").ToLower();
return ret;
}
And now let’s get the Gravatar and show it in the picturebox.
const string GURL = "http://www.gravatar.com/avatar/";
string tmp = GURL + MD5("dremation@gmail.com") + "?s=60&r=g&d=monsterid";
picGravatar.ImageLocation = tmp;
And there you have C# and VB .NET examples on how to retrieve a Gravatar using a users email address. This is nice because using this method is fast and simple.
Popularity: unranked [?]