
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)) & 1grid_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] = valpixels[y][4 - x] = val # 镜像到右边# Step 4: 创建图像img_size = sizecell_size = img_size // 5corner_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_sizey0 = y * cell_sizex1 = x0 + cell_sizey1 = y0 + cell_sizedraw.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 已生成!")
hash_hex = hashlib.md5(text.encode('utf-8')).hexdigest()"d41d8cd98f00b204e9800998ecf8427e")。color = tuple(int(hash_hex[i:i + 2], 16) for i in (0, 2, 4))hash_hex[0:6])作为颜色:hash_hex[0:2] → Rhash_hex[2:4] → Ghash_hex[4:6] → B"a1b2c3" → (161, 178, 195)for i in range(15):hex_char = hash_hex[6 + (i // 2)]bit = (int(hex_char, 16) >> (i % 2)) & 1grid_bits.append(bit)
ceil(15 / 2) = 8 个十六进制字符(即 hash_hex[6:14])。hex_char = 'a'(即 10,二进制 1010):i=0: 取 bit0 → 0i=1: 取 bit1 → 1pixels = [[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] = valpixels[y][4 - x] = val # 镜像到右边
background_color == 'transparent' → 使用 'RGBA' 模式,背景透明 (0,0,0,0)'RGB' 模式,指定背景色fill_color 为前面提取的 RGB(透明模式下加 alpha=255)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 的格子才绘制Python--数据/图像可视化(雷达图,甘特图,热力图)
细数那些经典教材(编程、数据结构与算法)
Python库巡礼(NumPy,Pandas,SciPy)
推荐文章