C#

Gravatar – Get avatar by email in C# and check available or not

gravatar.com is very popular now a days. So many large sites use this feature . I needed this feature in one of my working projects

But I needed to check also that email exists in Gravatar or not. If Gravatar does not have that email Id of the user , The app will show its custom Image . But If we call the Gravatar API , Gravatar sends a default image if that email is not available which was not our app’s behavior , so I needed to track and validate that.

UTF8Encoding encoder = new UTF8Encoding();
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(email));
            StringBuilder sb = new StringBuilder(hashedBytes.Length * 2);
            for (int i = 0; i < hashedBytes.Length; i++)
            {
                sb.Append(hashedBytes[i].ToString("X2"));
            }
            var imageHashCode = sb.ToString().ToLower();
            string gravatarImageUrl = "http://www.gravatar.com/avatar/" + imageHashCode + "?d=404";
            var uri = new Uri(gravatarImageUrl);
 
            using (WebClient client = new WebClient())
            {
                try
                {
                    var imageByte = client.DownloadData(uri);
                    var headers = client.ResponseHeaders;
                    if (headers != null && headers["Content-Disposition"] != null)
                    {
                        var header = headers["Content-Disposition"];
                        if (header.Contains(imageHashCode))
                        {
                            MemoryStream memoryStream = new MemoryStream(imageByte);
                            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(memoryStream);
                            BitmapSource image = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                            return image;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
                return null;
            }

Check the URL generation part in the code , I have used ?d=404 . This is the main thing which does the trick so that it returns 404 if that email address does not belong to Gravatar

But if anyone needs the default behavior of Gravatar , then just remove ?d=404 from the URL . It will show the default image if the email is not available.

Hope , this helps.

Cheers

Standard

Leave a Reply

Your email address will not be published. Required fields are marked *