Created
August 19, 2015 09:27
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Console.WriteLine(getGravitarImage("[email protected]")); | |
} | |
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