Skip to content

Instantly share code, notes, and snippets.

@Rooster212
Created August 19, 2015 09:27
Show Gist options
  • Save Rooster212/94f75582cf42509cfffc to your computer and use it in GitHub Desktop.
Save Rooster212/94f75582cf42509cfffc to your computer and use it in GitHub Desktop.
Gets a Gravitar image and returns the image as a 64bit string, or null if there is no image available
void Main()
{
Console.WriteLine(getGravitarImage("jamieroos1@googlemail.com"));
}
string getGravitarImage(string email)
{
MD5 md5hasher = MD5.Create();
byte[] data = md5hasher.ComputeHash(Encoding.Default.GetBytes(email.Trim().ToLower()));
StringBuilder builder = new StringBuilder();
foreach (var i in data)
builder.Append(i.ToString("x2"));
var gravitarHash = builder.ToString();
// GET parameters
// r = rating, g = G rated (suitable for all)
// d = image returned when there isn't an image for the email hash
// 404 = return a 404 when there is no image
var url = string.Format("http://www.gravatar.com/avatar/{0}?r=g&d=404", gravitarHash);
var imageBytes = getImageFromUrl(url);
return imageBytes != null ? Convert.ToBase64String(imageBytes) : null;
}
byte[] getImageFromUrl(string url)
{
byte[] buffer;
Stream stream = null;
try
{
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
stream = response.GetResponseStream();
using (BinaryReader reader = new BinaryReader(stream))
{
buffer = reader.ReadBytes((int)response.ContentLength);
reader.Close();
}
}
catch
{
buffer = null;
}
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment