根据人名生成随机头像的py和js实现

python实现

class AvatarUtil:
    colors = [
        "#31bc9f", "#33cc70", "#4a94db", "#9b5fb6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50",
        "#f1cb1e", "#e6761b", "#e7363b", "#00bcd4", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
    ]

    @staticmethod
    def create_font_img(username, img_size=50, img_bg_color=None):
        if not img_bg_color:
            avatar_color = AvatarUtil.colors[random.randint(1, len(AvatarUtil.colors))]
        else:
            avatar_color = img_bg_color

        output_buffer = BytesIO()
        img = Image.new('RGB', (img_size, img_size), avatar_color)  # 生成底图
        font_path = "static/song.ttf"  # 设置需要显示的字体
        font_size = int(img_size / 2)  # 字体取图片的一半
        font = ImageFont.truetype(font_path, size=font_size)
        # 部分字体的宽高不同,所以两个都需要获取,不然画出来会歪
        text_width, text_height = font.getsize(username[0])
        draw = ImageDraw.Draw(img)
        # 绘制文字信息,字体绘制的开始位置(x, y),(255,255,255) 为白色字体, font必须设置,不然字体大小没办法掌握
        draw.text(((img_size - text_width) / 2, (img_size - text_height) / 2), username[0], fill=(255, 255, 255),
                  font=font)
        img.save(output_buffer, format='png')  # 保存图片
        byte_data = output_buffer.getvalue()
        base64_str = base64.b64encode(byte_data).decode('utf-8')
        return f'data:image/png;base64,' + base64_str

js实现

请查看li大佬的文章
https://blog.csdn.net/mwqyykl/article/details/102465534
li大佬的实现有个问题就是他是随机生成的,每次都是不一样的颜色。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>根据用户名生成头像</title>
    <script src="js/main.js"></script>
</head>
<body>
    <img src="" style="border-radius: 50%;" id="userAvatar">
    <canvas id="avatarCanvas" style="display:none"></canvas>
</body>
    <script type="text/javascript">
        var username = "马";
        generatorAvator(username,60,null,"avatarCanvas","userAvatar");
    </script>
</html>
————————————————
版权声明:本文为CSDN博主「liouozm」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/mwqyykl/article/details/102465534
/**
 * usernmae : 用户名 默认为无
 * size :头像大小 默认为 30
 * color :字体颜色
 * canvasId :canvas容器的id
* */
function generatorAvator(username,size,bgcolor,canvasId,avatarContainerId){
    //设置头像昵称,如果为null或者为空时,设置为无
    var nickname = username==null?"无":username==""?"无":username;
    //设置头像大小
    var avatarSize = size==null?30:size;

    //设置头像内部文字大小
    var fontSize = size==null?12:avatarSize/2;

    //设置头像内部字体
    var fontWeight = 'normal';

    //设置头像背景颜色
    var colors = [
        "#31bc9f", "#33cc70", "#4a94db", "#9b5fb6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50",
        "#f1cb1e", "#e6761b", "#e7363b", "#00bcd4", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
    ];
    var avatarColor = bgcolor==null?colors[Math.floor((Math.random()*colors.length))]:bgcolor==""?bgcolor:colors[Math.floor((Math.random()*colors.length))];

    /*根据id获取canvas
    * 如果为空,则创建新的canvas
    * */
    var canvas = document.getElementById(canvasId);

    if(canvas){
        canvas.remove();
    }else{
        var newcanvas = "<canvas id='"+canvasId+"' style='display:none'></canvas>";
        document.getElementsByName("body").append(newcanvas);
        canvas = document.getElementById(canvasId);
    }

    //初始化canvas设置
    canvas.width = avatarSize;
    canvas.height = avatarSize;
    var context = canvas.getContext('2d');

    //头像背景颜色设置
    context.fillStyle = avatarColor;
    context.fillRect(0, 0, canvas.width, canvas.height);

    //头像字体颜色设置
    context.fillStyle = '#FFFFFF';
    context.font = fontWeight + ' ' + fontSize + 'px sans-serif';
    context.textAlign = 'center';
    context.textBaseline="middle";
    console.log(avatarSize/2-fontSize/2);
    console.log(avatarSize/2);

    context.fillText(nickname.charAt(0), fontSize, fontSize);
    document.getElementById(avatarContainerId).src = canvas.toDataURL("image/png");
}
————————————————
版权声明:本文为CSDN博主「liouozm」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/mwqyykl/article/details/102465534
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值