2010-01-20 5 views

Répondre

88

Lors de la construction de l'URL, utilisez le paramètre d = 404. Cela provoquera Gravatar pour renvoyer une erreur 404 plutôt qu'une image si l'utilisateur n'a pas défini une image.

Si vous utilisez le contrôle .Net lié au site gravitar, vous devrez modifier l'énumération IconSet (et probablement retirer le code du contrôle, afin que vous puissiez accéder directement au statut).

+4

-> http://www.gravatar.com/avatar/aaa?default=404 – thijs

+0

C'est une réponse beaucoup plus propre que tout le reste. Comme ça - paie pour lire la documentation, il semblerait. – Paddy

+0

Une fois que vous avez le 404, comment le transformez-vous en gravatar = false? – woodenfox

6

Ce que je l'ai fait:

  • Générez un gravatar avec adresse d'email
  • non-existante Enregistrer l'image
  • Faire une somme de contrôle MD5 des images contenus et le stocker comme une constante dans votre Code app

Après que je l'ai fait pour chaque demande gravatar:

  • Télécharger l'image gravatar
  • checksum MD5 le contenu et la comparer à la
  • constante Si elle correspond à c'est l'image par défaut, si elle ne le fait pas, il est une image personnalisée

Je mises en cache aussi la Gravatar image pendant 24 heures afin que vous ne devez pas compter sur gravatar tout le temps. En option, vous pouvez placer les 3 premiers points dans une fonction et la laisser s'exécuter de temps en temps pour s'assurer que gravatar utilise toujours la même image par défaut, même s'ils ne l'ont pas fait depuis au moins deux mois.

+0

Très bon idea..What est une somme de contrôle MD5? – Luke101

+0

La somme de contrôle MD5 est un hachage MD5 du contenu complet du fichier; Extrait de code pour C# ici: http: // sharpertutorials.com/calculate-md5-checksum-file/ – fijter

+0

La réponse choisie est bien meilleure mais cette astuce est utile dans certains cas. Par exemple en Javascript sur une page Web ou une extension de navigateur si vous ne voulez pas que votre navigateur enregistre une erreur "404 introuvable" dans les outils de développement. –

3

En 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; 
} 
+0

Existe-t-il un traducteur de code en ligne pour transformer ceci en C#? – Luke101

+0

@ Luke101: Je ne sais pas, et je donne encore les premiers pas en C#. Pardon. –

+0

Pourquoi la vérification d'égalité à 02dcccdb0707f1c5acc9a0369ac24dac? – adrianbanks

2

En C#, basé sur le code PHP posté plus tôt (non testé - code source pré-déjeuner suit):

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"); 
} 
1

Je fais actuellement quelque chose de similaire. J'ai une configuration de table pour les profils d'utilisateurs et dans cette table j'ai une colonne appelée Avatar. C'est ici que l'URL de Gravatar sera stockée. Le code suivant est ce que j'utilise pour gérer cette colonne.

// 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); 
} 

Cela semble fonctionner plutôt bien pour moi. J'ai toujours un avatar par défaut, et quand un utilisateur veut afficher son avatar personnalisé, il associe son email Gravatar (que je hash et ne stocke jamais en tant qu'adresse email) qui crée une URL que je peux déposer comme imageURL . Lorsque l'utilisateur supprime son lien Gravatar, j'annule la colonne de la base de données et l'imageURL revient à mon image par défaut.

Bonne chance et j'espère que cela vous aidera.

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"); 
     } 
    } 
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; 

} 
Questions connexes