实现网站剩余默认头像显示为首字头像(LetterAvatar)

基于canvas 动态生成 base64 图,配合本地缓存功能,判断使用了默认头像(即无Gravatar无QQ头像),为该无头图片添加特定的 class ,然后通过 LetterAvatar 脚本在访客浏览器上替换图片。

头像显示的字或字母默认是读取图片标签的 alt 属性内容的首字。WordPress 默认情况下get_avatar 内 alt=“” ,如果是在评论循环中即一般情况文章或页面下的评论模块可以直接使用 get_comment_author();或 get_the_author_meta(“display_name”); 来获取评论者昵称填充 alt 的值,get_avatar 钩子中可以反推出邮箱或注册的用户ID等在评论循环列表中也可以方便的调用。

<?php
function mk_get_avatar_name($id_or_email) {
//https://github.com/mengkunsoft/mk-letter-avatar
//尝试取出头像对应的用户名
    $user = null;
    if(empty($id_or_email)) {
        return null;
    } else if(is_object($id_or_email)) {
        if(!empty($id_or_email->comment_author)) {
            return $id_or_email->comment_author;
        } else if(!empty($id_or_email->user_id)) {
            $id = (int) $id_or_email->user_id;
            $user = get_user_by('id', $id);
        }
    } else if(is_numeric($id_or_email)) {
        $id = (int) $id_or_email; //是数字,尝试获取该 ID 对应的用户名
        $user = get_user_by('id', $id);
    } else if(is_string($id_or_email)) {
        if (!filter_var($id_or_email, FILTER_VALIDATE_EMAIL)) { 
            return $id_or_email;// 不是邮箱,当做用户名
        } else {
            $user = get_user_by('email', $email);
        }
    }
    if(!empty($user) && is_object($user)) {
        return $user->display_name;    // 尝试从用户对象中取出用户名
    }
    return null;
}
?>

但是也有局限性,比如本站评论榜等页面就没法使用,非注册用户的评论昵称还需要更多SQL查询,感觉效率太低没有进一步研究。我选择的是在做这些页面或小工具等,在查询获取头像的同时获取用户昵称,在输出前做一个替换。此情况没有直接搞到 get_avatar 钩子里,不能全局也挺麻烦的,得每个用到的页面和功能都改一遍。

替换添加 alt 标签值就是像

                                       
 $avatar = preg_replace('/alt=[\'\"][^\'\"]*?[\'\"]/isU','alt=\''.$comment->comment_author.'\'',$avatar);  

以下是使用到的JavaScript脚本,可自行设定字体颜色等等。

<script>
    /*
     * LetterAvatar
     * 
     * Artur Heinze
     * Create Letter avatar based on Initials
     * https://github.com/daolavi/LetterAvatar
     * based on https://gist.github.com/leecrossley/6027780
     */

    (function(w, d){
        function LetterAvatar (name, size, color) {
            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).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 = color ? color : colours[colourIndex - 1];
            context.fillRect (0, 0, canvas.width, canvas.height);
            context.font = Math.round(canvas.width/1.6)+"px Arial";
            context.textAlign = "center";
            context.fillStyle = "#FFF";
            context.fillText(initials, size / 2, size / 1.4);

            dataURI = canvas.toDataURL();
            canvas  = null;

            return dataURI;
        }

        LetterAvatar.transform = function() {
           //对应的头像所在标签的类名称
            Array.prototype.forEach.call(d.querySelectorAll('.mydeftoux'), function(img, name, color) {
                name = img.getAttribute('alt');
                color = img.getAttribute("#1abc9c");
                img.src = LetterAvatar(name, 100, color);
            });
        };
        // 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>

密密麻麻看得也是云里雾里,对应地再改一下自己使用的 class 名称即可把它运行起来了。

具体的实现还得结合本站之前的文章:网站评论者头像接入QQ头像并缓存本地,因为默认把无头像的统一换成了一张固定的图片,因此直接比较图片大小即可判断是否使用了默认图片。万一出现两张不同图片大小一样的情况只能~%*&,毕竟概率太低,小破站没必要追究得这么清楚。

没得到就是最香的,之前还乐此不疲的折腾某博友的插件,通过刻意大量制造404请求的方式触发替换图片 无法忍受,效果也不理想,JS代码混淆看不明白,当时在本地缓存都没搞明白的情况下只能放弃,毕竟经过测试每次都进行是否有头像判断会严重拖累网站正常运行速度。现在轮子造好了最初的热情也消退了。

以下是本站胡乱搞后的显示效果:

《实现网站剩余默认头像显示为首字头像(LetterAvatar)》
《实现网站剩余默认头像显示为首字头像(LetterAvatar)》
《实现网站剩余默认头像显示为首字头像(LetterAvatar)》

太花花绿绿,发现显示默认头像也挺好看的,可能把底色直接统一成灰色会好点吧,以后慢改,暂时不上线该首字头像功能。

回复 郑永 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

  1. 学徒 学徒 说道:

    站长,你好,我也发愁mk letter avatar插件,评论榜等页面就没法使用。你这个帖子很好,只看明白一点点,请问你能出个教程吗?

  2. 流量卡 流量卡 说道:

    能不能适用zb

    1. 黑鸟 说道:

      不能,原理可以借鉴,代码需要很多修改。

  3. 沉舟侧畔 说道:

    其实我发现,wordpress默认的随机小怪物头像也挺好看的

    1. 黑鸟 说道:

      不喜欢小怪物,直接默认的灰白头像干脆点。

  4. 荣达科技 荣达科技 说道:

    这个很强大,头像越来越好看

    1. 黑鸟 说道:

      只是有时候需要多点色彩点缀下

  5. WordPress新手学园 说道:

    这个方法确实是不错,对于那些没有内置默认头像的站点来说确实是是有效果的

  6. 黑鸟 说道:

    如果从大部分人取名字或昵称的惯例看,最后一个字才更加重要,或者说更符合单个个体的区别点,突出点。YouTube头像就是这么做的。
    并且有汉字和其他字符混合的时候优先过滤出汉字显示,毕竟单个英文字母基本表达不了什么特殊含义。

  7. 郑永 说道:

    看着密密麻麻又工整很舒服哈,效果不错。

    1. 黑鸟 说道:

      配色太鲜艳都盖过正常头像的,就是不想一堆默认头像那么寂寞,喧宾夺主更加不能忍。