37

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

4

7 回答 7

95

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

如果您使用从 gravitar 站点链接到的 .Net 控件,则需要修改 IconSet 枚举(并且可能将代码从控件中拉出,以便您可以直接获取状态)。

于 2010-01-24T21:55:04.910 回答
6

我做了什么:

  • 使用不存在的电子邮件地址生成 gravatar
  • 保存图像
  • 对图像内容进行 MD5 校验,并将其作为常量存储在您的应用代码中

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

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

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

于 2010-01-24T12:58:04.367 回答
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;
}
于 2010-01-25T01:52:48.853 回答
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");
}
于 2010-01-26T12:06:55.137 回答
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 电子邮件(我散列并且从不存储为电子邮件地址),这会创建一个 URL,我可以将其作为 imageURL 放入. 当用户删除他们的 gravatar 链接时,我会将数据库列清空,并且 imageURL 会返回到我的默认图像。

祝你好运,希望这对你有所帮助。

于 2010-01-28T02:10:50.780 回答
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");
        }
    }
于 2011-03-18T11:19:37.727 回答
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;

}
于 2012-05-19T07:13:51.630 回答