Gravatar:我如何知道用户是否有真实照片

时间:2010-01-20 17:50:23

标签: c# gravatar

我已经在我的网站上运行了gravatar服务。但我想知道用户是否上传了他们的照片。有没有办法知道这个?

7 个答案:

答案 0 :(得分:88)

构建URL时,请使用参数d = 404。如果用户没有设置图片,这将导致Gravatar返回404错误而不是图像。

如果你正在使用从gravitar网站链接的.Net控件,你需要修改IconSet枚举(并且可能会将代码从控件中拉出来,这样你就可以直接获得状态了。) / p>

答案 1 :(得分:6)

我做了什么:

  • 使用不存在的电子邮件
  • 生成一个gravatar
  • 保存图片
  • 制作图像内容的MD5校验和,并将其作为常量存储在应用代码中

之后,我为每个gravatar请求执行此操作:

  • 下载gravatar图片
  • MD5校验内容并将其与常量
  • 进行比较
  • 如果匹配则为默认图像,如果不匹配,则为自定义图像

我还将gravatar图像缓存了24小时,因此您不必一直依赖gravatar。可选地,你可以将前3个点放在一个函数中并让它偶尔运行一次,以确保gravatar仍然使用相同的默认图像,尽管它们至少在过去几个月内没有(可能永远不会)。

答案 2 :(得分:3)

在PHP中:

function hasGravatar($email)
{
    return (md5(file_get_contents(sprintf('http://www.gravatar.com/avatar/%s?default=identicon&size=32', md5($email)))) == '02dcccdb0707f1c5acc9a0369ac24dac') ? false : true;
}

答案 3 :(得分:2)

在C#中,基于之前发布的PHP代码(未经测试 - 午餐前的源代码如下):

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Net.WebClient;

public string GenerateMD5(string plaintext)
{
    Byte[] _originalBytes;
    Byte[] _encodedBytes;
    MD5 _md5;

    _md5 = new MD5CryptoServiceProvider();
    _originalBytes = ASCIIEncoding.Default.GetBytes(plaintext);
    _encodedBytes = _md5.ComputeHash(_originalBytes);

  return BitConverter.ToString(_encodedBytes).ToLower();
}

public string file_get_contents(string url) 
{ 
    string sContents = string.Empty; 

    if (url.ToLower().IndexOf("http:") > -1) {
        System.Net.WebClient wc = new System.Net.WebClient(); 
        byte[] response = wc.DownloadData(url); 
        sContents = System.Text.Encoding.ASCII.GetString(response); 
    } else { 
        System.IO.StreamReader sr = new System.IO.StreamReader(url); 
        sContents = sr.ReadToEnd(); 
        sr.Close(); 
    } 

    return sContents;
}

public bool hasGravatar(string email)
{
    string _mailMD5 = GenerateMD5(email);
    string _url = String.Format("http://www.gravatar.com/avatar/{0}?default=identicon&size=32", _mailMD5);
    string _fileMD5 = GenerateMD5(file_get_contents(_url));

    return !(_fileMD5 == "02dcccdb0707f1c5acc9a0369ac24dac");
}

答案 4 :(得分:1)

我目前正在做类似的事情。我有一个用户配置文件的表设置,在该表中我有一个名为Avatar的列。这是存储Gravatar URL的地方。以下代码是我用来管理此列的代码。

// first gather the email address that is going to be associated with this user as
// their gravatar.
// once you have gathered the email address send it to a private method that
// will return the correct url format.
protected void uxAssocateAvatar_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
    string emailAddress = uxEmailAddress.Text;
    try
    {
        Profile.Avatar = GetGravatarUrl(emailAddress);
        Profile.Save();
        Response.Redirect("Settings.aspx", true);
    }
    catch (Exception ex)
    {
        ProcessException(ex, Page);
    }
}
}

// use this private method to hash the email address, 
// and then create the url to the gravatar service.
private string GetGravatarUrl(string dataItem)
{
    string email = dataItem;
    string hash =
        System.Web.Security.FormsAuthentication.
        HashPasswordForStoringInConfigFile(email.Trim(), "MD5");
    hash = hash.Trim().ToLower();
    string gravatarUrl = string.Format(
       "http://www.gravatar.com/avatar.php?gravatar_id={0}&rating=G&size=100",
        hash);
    return gravatarUrl;
}

// on the page where an avatar will be displayed, 
// just drop in an asp.net image control with a default image.
<asp:Image ID="uxAvatar" runat="server" ImageUrl="~/images/genericProfile.jpg"
AlternateText="" CssClass="profileAvatar" BorderWidth="1px"/>

// and on page_load or something like that, 
// check to see if the profile's avatar property is set 
if (Profile.Avatar != null)
{
    uxAvatar.ImageUrl = Profile.Avatar;
}

// by default the profile's avatar property will be null, and when a user decides
// that they no longer want an avatar, the can de-associate it by creating a null 
// property which can be checked against 
// to see if they have one or don't have one.
protected void uxRemoveAvatar_Click(object sender, EventArgs e)
{
    Profile.Avatar = null;
    Profile.Save();
    Response.Redirect("Settings.aspx", true);
}

这似乎对我来说非常好。我总是有一个默认的头像显示,当用户实际想要显示他们的自定义头像时,他们将他们的Gravatar电子邮件(我哈希并且从不存储为电子邮件地址)关联起来,这会创建一个我可以作为imageURL放入的URL 。当用户删除其gravatar链接时,我将数据库列清空,imageURL返回到我的默认图像。

祝你好运,希望这可以帮助你。

答案 5 :(得分:1)

private bool HasUserPublicGravatar(string email)
    {
        try
        {
            var gravatarPath = GravatarService.GetGravatarUrlForAddress(email,
            new GravatarUrlParameters { DefaultOption = GravatarDefaultUrlOptions.Error });

            WebRequest wReq = HttpWebRequest.Create(gravatarPath);
            var wRes = wReq.GetResponse();
            return true;
        }
        catch (System.Net.WebException ex)
        {
            if (ex.Message.Contains("404"))
                return false;
            else
                throw new Exception("Couldn't determine if ueser has public avatar");
        }
    }

答案 6 :(得分:0)

function get_gravatar( $email, $s = 80, $d = '404', $r = 'x', $img = false, $atts = array() ) {

$url = 'http://www.gravatar.com/avatar/';
$url .= md5(strtolower(trim($email)));
$url .= "?s=$s&d=$d&r=$r";

if ( $img ) 
{
$url = '<img src="' . $url . '"';
foreach ( $atts as $key => $val )
$url .= ' ' . $key . '="' . $val . '"';
$url .= ' />';
return $url;

}

$headers = @get_headers($url);

if (!preg_match("|200|", $headers[0])) 
{
$has_valid_avatar = 'no';
} 
else 
{
$has_valid_avatar = 'yes';
}

return $has_valid_avatar;

}