Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1048453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T16:27:28+00:00 2026-05-16T16:27:28+00:00

Whilst the Gravatar service’s API (well, it’s really just a URL) is pretty straightforward,

  • 0

Whilst the Gravatar service’s API (well, it’s really just a URL) is pretty straightforward, is there a simple helper method out there that does a good job of reflecting all the options available for Gravatar?

  • Image size
  • Default image (when user hasn’t specified one)
  • Rating (G/PG/R/X)

Ideally this would be an HtmlHelper extension method.

I’m targetting MVC2 on .NET4, but I suppose others would be interested in options for earlier versions too.

EDIT Implementations should allow providing additional attributes for the generated HTML element too.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T16:27:29+00:00Added an answer on May 16, 2026 at 4:27 pm

    Thanks for your answers. In the end I wrote my own solution, so I’ll post it here for anyone else who might find it useful.

    It caters for all the functionality Gravatar supports right now, as listed in the question.

    Use it like this:

    <%= Html.Gravatar(Model.User.EmailAddress) %>
    

    I provided optional arguments for any, er, options. These can be combined.

    // Use a specific image size (the default is 80px)
    Html.Gravatar(Model.User.EmailAddress, size:64)
    
    // Specify what image should appear if the email address is not
    // associated with a Gravatar account
    Html.Gravatar(Model.User.EmailAddress,
                  defaultImage:GravatarDefaultImage.Identicon)
    
    // Specify the maximum rating allowed for images
    Html.Gravatar(Model.User.EmailAddress, rating:GravatarRating.Pg)
    
    // Add any additional HTML attributes for the <img /> tag
    Html.Gravatar(Model.User.EmailAddress,
                  htmlAttributes:new { @class = "gravatar" })
    

    Here’s the code:

    using System;
    using System.Diagnostics;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace SampleNamespace
    {
        public static class HtmlHelperGravatar
        {
            /// <summary>
            /// Creates HTML for an <c>img</c> element that presents a Gravatar icon.
            /// </summary>
            /// <param name="html">The <see cref="HtmlHelper"/> upon which this extension method is provided.</param>
            /// <param name="email">The email address used to identify the icon.</param>
            /// <param name="size">An optional parameter that specifies the size of the square image in pixels.</param>
            /// <param name="rating">An optional parameter that specifies the safety level of allowed images.</param>
            /// <param name="defaultImage">An optional parameter that controls what image is displayed for email addresses that don't have associated Gravatar icons.</param>
            /// <param name="htmlAttributes">An optional parameter holding additional attributes to be included on the <c>img</c> element.</param>
            /// <returns>An HTML string of the <c>img</c> element that presents a Gravatar icon.</returns>
            public static string Gravatar(this HtmlHelper html,
                                          string email, 
                                          int? size = null,
                                          GravatarRating rating = GravatarRating.Default,
                                          GravatarDefaultImage defaultImage = GravatarDefaultImage.MysteryMan,
                                          object htmlAttributes = null)
            {
                var url = new StringBuilder("//www.gravatar.com/avatar/", 90);
                url.Append(GetEmailHash(email));
    
                var isFirst = true;
                Action<string,string> addParam = (p,v) =>
                    {
                        url.Append(isFirst ? '?' : '&');
                        isFirst = false;
                        url.Append(p);
                        url.Append('=');
                        url.Append(v);
                    };
    
                if (size != null)
                {
                    if (size < 1 || size > 512)
                        throw new ArgumentOutOfRangeException("size", size, "Must be null or between 1 and 512, inclusive.");
                    addParam("s", size.Value.ToString());
                }
    
                if (rating != GravatarRating.Default)
                    addParam("r", rating.ToString().ToLower());
    
                if (defaultImage != GravatarDefaultImage.Default)
                {
                    if (defaultImage==GravatarDefaultImage.Http404)
                        addParam("d", "404");
                    else if (defaultImage==GravatarDefaultImage.Identicon)
                        addParam("d", "identicon");
                    if (defaultImage==GravatarDefaultImage.MonsterId)
                        addParam("d", "monsterid");
                    if (defaultImage==GravatarDefaultImage.MysteryMan)
                        addParam("d", "mm");
                    if (defaultImage==GravatarDefaultImage.Wavatar)
                        addParam("d", "wavatar");
                }
    
                var tag = new TagBuilder("img");
                tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
                tag.Attributes.Add("src", url.ToString());
    
                if (size!=null)
                {
                    tag.Attributes.Add("width", size.ToString());
                    tag.Attributes.Add("height", size.ToString());
                }
    
                return tag.ToString();
            }
    
            private static string GetEmailHash(string email)
            {
                if (email == null)
                    return new string('0', 32);
    
                email = email.Trim().ToLower();
    
                var emailBytes = Encoding.ASCII.GetBytes(email);
                var hashBytes = new MD5CryptoServiceProvider().ComputeHash(emailBytes);
    
                Debug.Assert(hashBytes.Length == 16);
    
                var hash = new StringBuilder();
                foreach (var b in hashBytes)
                    hash.Append(b.ToString("x2"));
                return hash.ToString();
            }
        }
    
        public enum GravatarRating
        {
            /// <summary>
            /// The default value as specified by the Gravatar service.  That is, no rating value is specified
            /// with the request.  At the time of authoring, the default level was <see cref="G"/>.
            /// </summary>
            Default,
    
            /// <summary>
            /// Suitable for display on all websites with any audience type.  This is the default.
            /// </summary>
            G,
    
            /// <summary>
            /// May contain rude gestures, provocatively dressed individuals, the lesser swear words, or mild violence.
            /// </summary>
            Pg,
    
            /// <summary>
            /// May contain such things as harsh profanity, intense violence, nudity, or hard drug use.
            /// </summary>
            R,
    
            /// <summary>
            /// May contain hardcore sexual imagery or extremely disturbing violence.
            /// </summary>
            X
        }
    
        public enum GravatarDefaultImage
        {
            /// <summary>
            /// The default value image.  That is, the image returned when no specific default value is included
            /// with the request.  At the time of authoring, this image is the Gravatar icon.
            /// </summary>
            Default,
    
            /// <summary>
            /// Do not load any image if none is associated with the email hash, instead return an HTTP 404 (File Not Found) response.
            /// </summary>
            Http404,
    
            /// <summary>
            /// A simple, cartoon-style silhouetted outline of a person (does not vary by email hash).
            /// </summary>
            MysteryMan,
    
            /// <summary>
            /// A geometric pattern based on an email hash.
            /// </summary>
            Identicon,
    
            /// <summary>
            /// A generated 'monster' with different colors, faces, etc.
            /// </summary>
            MonsterId,
    
            /// <summary>
            /// Generated faces with differing features and backgrounds.
            /// </summary>
            Wavatar
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Whilst I don't have no ANALYSE issues with my iPhone code, when I run
Should one lock a UITableView whilst it is updating somehow? That is, during a
If i was to store some order details in a session whilst the customer
I have been working on making my website mobile compatible. Whilst I have successfully
I have seen several solutions which determine when an element is visible in the
Is it possible to do a preg_match() on something that shouldn't be a match
I have been making a matrix class (as a learning exercise) and I have
I think I have run into a bug in Mojarra 2.1.0. Maybe I missed
Possible Duplicate: How to enable or disable an anchor using jQuery? I've got an
My previous question How to wrap Wicket page rendering in a Spring / Hibernate

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.