Letter Avatar

How to easily create letter avatars for your comments in Orchard CMS 1.8.1+.

Got really tired of the Gravatar Service being down or slow and having multiple server calls to download the Gravatar. Alot of people do not even know about gravatar and your get a generic image for the User Avatar.

After searching around the net for a while I found several ruby gems to do this and a lot of WordPress add-ons. A simple implementation eluded me. Then I found this CodePen with a GetHub link to Lee Crossley's GitHub page which I added to my PJS.Bootstrap theme. PJS.Bootstarp already had a Alternitive shape called CommentGravatar.cshtml, so I just rebuilt the alternative shape to be able to use the CodePen Letter Avatar adding a simple script for the letter avatars.

A image from a comment where the user did not have a avatar.

The same Comment with Letter Avatar

A much cleaner implimentation with no download overhead. The background colours are from from http://flatuicolors.com/ Now with retina support.

The Javascript
(function (w, d) {
 
 
        function LetterAvatar(name, size) {
 
            name = name || '';
            size = size || 60;
 
            var colours = [
                    "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50",
                    "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
            ],
 
                nameSplit = String(name).toUpperCase().split(' '),
                initials, charIndex, colourIndex, canvas, context, dataURI;
 
 
            if (nameSplit.length == 1) {
                initials = nameSplit[0] ? nameSplit[0].charAt(0) : '?';
            } else {
                initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
            }
 
            if (w.devicePixelRatio) {
                size = (size * w.devicePixelRatio);
            }
 
            charIndex = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
            colourIndex = charIndex % 20;
            canvas = d.createElement('canvas');
            canvas.width = size;
            canvas.height = size;
            context = canvas.getContext("2d");
 
            context.fillStyle = colours[colourIndex - 1];
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.font = Math.round(canvas.width / 2) + "px Arial";
            context.textAlign = "center";
            context.fillStyle = "#FFF";
            context.fillText(initials, size / 2, size / 1.5);
 
            dataURI = canvas.toDataURL();
            canvas = null;
 
            return dataURI;
        }
 
        LetterAvatar.transform = function () {
 
            Array.prototype.forEach.call(d.querySelectorAll('img[avatar]'), function (img, name) {
                name = img.getAttribute('avatar');
                img.src = LetterAvatar(name, img.getAttribute('width'));
                img.removeAttribute('avatar');
                img.setAttribute('alt', name);
            });
        };
 
 
        // AMD support
        if (typeof define === 'function' && define.amd) {
 
            define(function () { return LetterAvatar; });
 
            // CommonJS and Node.js module support.
        } else if (typeof exports !== 'undefined') {
 
            // Support Node.js specific `module.exports` (which can be a function)
            if (typeof module != 'undefined' && module.exports) {
                exports = module.exports = LetterAvatar;
            }
 
            // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
            exports.LetterAvatar = LetterAvatar;
 
        } else {
 
            window.LetterAvatar = LetterAvatar;
 
            d.addEventListener('DOMContentLoaded', function (event) {
                LetterAvatar.transform();
            });
        }
 
    })(window, document);
	
The full code of CommentGravatar.cshtml with changes from Gravatar to Letter Avatar.
@using Orchard.Comments.Models
@using Orchard.ContentManagement
@using Orchard.Users.Models
 
@{
    CommentPart comment = Model.ContentPart;
    string userName = string.Empty;
 
    if (String.IsNullOrWhiteSpace(comment.UserName)) {
        userName = comment.Author;
    }
    else {
        var cm = WorkContext.Resolve<IContentManager>();
        var user = cm.Query<UserPart, UserPartRecord>().Where(x => x.NormalizedUserName == comment.UserName)
        .List().FirstOrDefault();
 
        if (user != null) {
            userName = comment.Author;
        }
    }
 
}
 
<img itemprop="image" src="#" avatar="@comment.Author" alt="@comment.Author" class="media-object" />
<script type="text/javascript">
    (function (w, d) {
 
 
        function LetterAvatar(name, size) {
 
            name = name || '';
            size = size || 60;
 
            var colours = [
                    "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", 
                    "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", 
                    "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
            ],
 
                nameSplit = String(name).toUpperCase().split(' '),
                initials, charIndex, colourIndex, canvas, context, dataURI;
 
 
            if (nameSplit.length == 1) {
                initials = nameSplit[0] ? nameSplit[0].charAt(0) : '?';
            } else {
                initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
            }
 
            if (w.devicePixelRatio) {
                size = (size * w.devicePixelRatio);
            }
 
            charIndex = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
            colourIndex = charIndex % 20;
            canvas = d.createElement('canvas');
            canvas.width = size;
            canvas.height = size;
            context = canvas.getContext("2d");
 
            context.fillStyle = colours[colourIndex - 1];
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.font = Math.round(canvas.width / 2) + "px Arial";
            context.textAlign = "center";
            context.fillStyle = "#FFF";
            context.fillText(initials, size / 2, size / 1.5);
 
            dataURI = canvas.toDataURL();
            canvas = null;
 
            return dataURI;
        }
 
        LetterAvatar.transform = function () {
 
            Array.prototype.forEach.call(d.querySelectorAll('img[avatar]'), function (img, name) {
                name = img.getAttribute('avatar');
                img.src = LetterAvatar(name, img.getAttribute('width'));
                img.removeAttribute('avatar');
                img.setAttribute('alt', name);
            });
        };
 
 
        // AMD support
        if (typeof define === 'function' && define.amd) {
 
            define(function () { return LetterAvatar; });
 
            // CommonJS and Node.js module support.
        } else if (typeof exports !== 'undefined') {
 
            // Support Node.js specific `module.exports` (which can be a function)
            if (typeof module != 'undefined' && module.exports) {
                exports = module.exports = LetterAvatar;
            }
 
            // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
            exports.LetterAvatar = LetterAvatar;
 
        } else {
 
            window.LetterAvatar = LetterAvatar;
 
            d.addEventListener('DOMContentLoaded', function (event) {
                LetterAvatar.transform();
            });
        }
 
    })(window, document);
</script>
 

4 Comments

  • how much is A facebook ads account

    His goal were to also get rid of the inconvenience of bouncing from app to app to try and do different task's so there are plenty of functionality and creativity
    inside structure on the app. You can establish traffic by creating attractive content to your website.
    Facebook is attempting to drive using this design since they would like to create Facebook.

    • Don Boulton

      Which is not specific enough for user id's?

  • Google Ppc Account

    At first, google sets this to broad match.

  • Donald Trump Announcement Today Speech

    Historically along with literature there exists still no better method of expressing this than she hasn't been able to sell her soul, to "make an offer using the devil".
    If you do have a plan that's using your head asking you to
    do simply WORK IT. The very first time that his empire collapsed, he used his business contacts
    and knowledge, and created The Apprentice show

Comments are Moderated, from, "(Spam-bots)", before they are posted.

 1584819 Views