首页   

这个库才是真的牛逼,轻松搞定各种头像生成!

Python入门与进阶  ·  · 4 年前

来源:Python之禅,作者:刘志军

链接:https://mp.weixin.qq.com/s/YBV1cqPvUPSiuQjO43stvg

原谅我这个标题党,内容是纯正干货,就是希望你们能打开学习了解一下。

二十次幂网站的用户注册功能并没有要求上传头像,所有人使用的是一个默认头像。

这几天花把这块进行了优化,基于email的哈希值每个人都有唯一的头像了。使用 Flask-Avatars 提供的功能。


发现这个库非常强大,集成了很多功能在里面,各种各样的头像生成方案,有Identicon、 monsterid、Robohash 甚至是社交平台的头像,另外还支持裁减,这篇文章就来详细具体介绍一下。

安装

$ pip install flask-avatars

初始化

from flask import Flask
from flask_avatars import Avatars
app = Flask(__name__)

avatars = Avatars(app)

生成 Gravatar 头像

Gravatar是 Globally Recognized Avatar的缩写,是 gravatar 网站推出的一项服务,意为“全球通用头像”。GitHub、Stack Overflow、V2EX 等平台使用它作为用户默认的头像。


from flask import render_template
...

@app.route("/")
def hello():
import hashlib
avatar_hash = hashlib.md5("lzjun567@qq".lower().encode('utf-8')).hexdigest()
avatar_hash = avatars.gravatar(avatar_hash, default="wavatar")
return render_template("index.html", avatar_hash=avatar_hash)

if __name__ == '__main__':
app.run(port=8000)

在index.html模板中可以直接引用 avatars 实例

<html lang="en">
<body>
<img src="{{ avatars.gravatar(avatar_hash) }}">
body>
html>

这个头像的链接是来自于Gravatar网站,每个emai对应l唯一一个头像。

生成默认头像

"{{ avatars.default() }}">

生成Robohash头像

Robohash 头像是一种随机的机器人头像,可以直接使用 avatars.robohash() 生成 URL

"{{ avatars.robohash('mark') }}">

生成社交媒体头像

如果你在某些社交平台有自己的账号,那么只要指定自己的用户名可以拿到头像了。我们找一个在Twitter有账号的人试一下,例如:Fenng老师

"{{ avatars.social_media('Fenng', platform='twitter') }}">

支持的平台包括Twiiter,Facebook,还有 Instagram。

以上头像资源都保存在第三方平台,如果你想自己生成头像,并将它保存在本地,那么你可以使用 Identicon 类

哈希头像生成器

Identicon 基于用户信息的哈希值生成图像,通常使用用户登录时的邮箱地址作为输入值,并作为生成新建用户时的初始化头像用于保护用户隐私。

from flask_avatars import Identicon

@app.route("/")
def hello():
avatar = Identicon()
filenames = avatar.generate(text="lzjun")
return render_template("index.html", filenames=filenames)

if __name__ == '__main__':
app.config['AVATARS_SAVE_PATH'] = "./static/"
app.run(port=8000)

index.thml

{% for file in filenames %}
<img src="{{ url_for('static', filename=file)}}">
{% endfor %}

最后生成的图像效果:

另外,Flask Avatar 还支持裁剪。类似这样的效果


有没有觉得很强大,同意的点个“在看”! 

推荐阅读:

我的名片能运行Linux和Python,还能玩2048小游戏,成本只要20元

李子柒 的辣酱真的那么好吃?用Python带你多维度分析

PC客户端爬虫,这样设置代理就对了

超强算法:一张图让二次元妹纸活起来!



好文和朋友一起看~
推荐文章
面相八字看命运  ·  愿众生皆能得菩萨庇佑,阖家平安,无病无灾,违 ...  ·  1 年前  
生活知识讲堂  ·  十二生肖2021年运势判断,你的生肖是富贵命吗?  ·  3 年前  
投行泰山  ·  #泰山聊减肥# ...  ·  3 年前  
© 2022 51好读
删除内容请联系邮箱 2879853325@qq.com