当前位置:首页>python>Python编程小技巧--制作简易github风格头像

Python编程小技巧--制作简易github风格头像

  • 2026-08-26 09:00:44
Python编程小技巧--制作简易github风格头像
GitHub头像(Identicon)的生成原理其实挺巧妙的,它通过哈希算法把用户名或邮箱转换成一个唯一的、对称的像素图案,核心就是‌确定性算法‌和‌视觉对称性‌。
用Python就可以生成简易的github风格头像,先看下效果
代码如下(可直接运行)
import hashlibfrom PIL import Image, ImageDrawdef generate_identicon(        text,        size=200,        background_color=(255, 255, 255),  # 默认白色背景        corner_radius_ratio=0.2  # 圆角比例(相对于 cell_size)):    # Step 1: 生成 MD5 哈希    hash_hex = hashlib.md5(text.encode('utf-8')).hexdigest()    # Step 2: 提取颜色(RGB)    color = tuple(int(hash_hex[i:i + 2], 16) for i in (0, 2, 4))    # Step 3: 构建 5x5 对称网格    grid_bits = []    for i in range(15):        # 从哈希的第6位开始取(跳过颜色部分)        hex_char = hash_hex[6 + (i // 2)]        bit = (int(hex_char, 16) >> (i % 2)) & 1        grid_bits.append(bit)    pixels = [[0] * 5 for _ in range(5)]    for y in range(5):        for x in range(3):  # 左半边(含中轴)            val = grid_bits[y * 3 + x]            pixels[y][x] = val            pixels[y][4 - x] = val  # 镜像到右边    # Step 4: 创建图像    img_size = size    cell_size = img_size // 5    corner_radius = int(cell_size * corner_radius_ratio)    corner_radius = min(corner_radius, cell_size // 2)  # 限制最大圆角    # 支持透明背景    if background_color == 'transparent':        img = Image.new('RGBA', (img_size, img_size), (0, 0, 0, 0))        draw = ImageDraw.Draw(img)        fill_color = (*color, 255)  # 不透明前景    else:        img = Image.new('RGB', (img_size, img_size), background_color)        draw = ImageDraw.Draw(img)        fill_color = color    # 绘制每个格子    for y in range(5):        for x in range(5):            if pixels[y][x]:                x0 = x * cell_size                y0 = y * cell_size                x1 = x0 + cell_size                y1 = y0 + cell_size                draw.rounded_rectangle(                    [x0, y0, x1, y1],                    radius=corner_radius,                    fill=fill_color                )    return img# 示例使用if __name__ == "__main__":    # 示例1:白色背景 + 圆角    img1 = generate_identicon("alice", size=200, background_color=(240, 240, 240), corner_radius_ratio=0.2)    img1.save("identicon_alice.png")    # 示例2:深色背景    img2 = generate_identicon("bob", size=200, background_color=(30, 30, 30), corner_radius_ratio=0.3)    img2.save("identicon_bob.png")    # 示例3:透明背景(RGBA)    img3 = generate_identicon("charlie", size=200, background_color='transparent', corner_radius_ratio=0.25)    img3.save("identicon_charlie.png")  # 保存为 PNG 以保留透明度    print("Identicons 已生成!")

算法流程详解

Step 1: 生成 MD5 哈希

hash_hex = hashlib.md5(text.encode('utf-8')).hexdigest()
  • 将输入文本转为 UTF-8 字节串,计算 MD5,得到 32 位十六进制字符串(如 "d41d8cd98f00b204e9800998ecf8427e")。

Step 2: 提取 RGB 颜色

color = tuple(int(hash_hex[i:i + 2], 16) for i in (0, 2, 4))
  • 取哈希前 6 位(即 hash_hex[0:6])作为颜色:
    • hash_hex[0:2] → R
    • hash_hex[2:4] → G
    • hash_hex[4:6] → B
  • 例如:"a1b2c3" → (161, 178, 195)

Step 3: 构建 5×5 对称像素网格

(a) 从哈希中提取 15 个二进制位
for i in range(15):    hex_char = hash_hex[6 + (i // 2)]    bit = (int(hex_char, 16) >> (i % 2)) & 1    grid_bits.append(bit)
  • 从第 7 位开始(索引 6),每 1 个十六进制字符(4 位)可提供 2 个比特(因为只用最低 2 位)。
  • 共需 15 位(5 行 × 3 列 = 15 个单元格),所以需要 ceil(15 / 2) = 8 个十六进制字符(即 hash_hex[6:14])。
  • 例如:hex_char = 'a'(即 10,二进制 1010):
    • i=0: 取 bit0 → 0
    • i=1: 取 bit1 → 1
(b) 构建对称网格
pixels = [[0]*5 for _ in range(5)]for y in range(5):    for x in range(3):  # x=0,1,2(左半+中轴)        val = grid_bits[y*3 + x]        pixels[y][x] = val        pixels[y][4 - x] = val  # 镜像到右边
  • 每行只定义前 3 列(x=0,1,2),第 4 列(x=3)镜像 x=1,第 5 列(x=4)镜像 x=0。
  • 结果是一个 左右对称 的 5×5 二值矩阵(0/1)。

Step 4: 渲染图像

(a) 创建画布
  • 若 background_color == 'transparent' → 使用 'RGBA' 模式,背景透明 (0,0,0,0)
  • 否则 → 'RGB' 模式,指定背景色
  • 前景色 fill_color 为前面提取的 RGB(透明模式下加 alpha=255)
(b) 绘制圆角矩形
cell_size = size // 5corner_radius = int(cell_size * corner_radius_ratio)...draw.rounded_rectangle([x0, y0, x1, y1], radius=corner_radius, fill=fill_color)
  • 每个“像素”是一个 cell_size × cell_size 的方块
  • 使用 rounded_rectangle 实现圆角效果(现代 PIL/Pillow 支持)
  • 只有 pixels[y][x] == 1 的格子才绘制

推荐合集

推荐文章

最新文章

随机文章