In this article I will show and tell you how you can generate avatars like on Github.
First you need to understand how the Github avatar works. At first glance, this is just a random collection of shaded squares (hereinafter, blocks) in a good order on a gray background.
Each avatar has 12 by 12 blocks.
, , , 6 12, , 12 12.
, , . python.
from PIL import ImageDraw, Image
import numpy as np
import hashlib
background_color = '#f2f1f2'
s = 'test1'
. - , , .
bytes = hashlib.md5(s.encode('utf-8')).digest()
main_color = bytes[:3]
main_color = tuple(channel // 2 + 128 for channel in main_color) # rgb
, . 6 12, , :
# 6 12
need_color = np.array([bit == '1' for byte in bytes[3:3+9] for bit in bin(byte)[2:].zfill(8)]).reshape(6, 12)
# 12 12
need_color = np.concatenate((need_color, need_color[::-1]), axis=0)
img_size = (avatar_size, avatar_size)
block_size = avatar_size // 12 #
img = Image.new('RGB', img_size, background_color)
draw = ImageDraw.Draw(img)
for x in range(avatar_size):
for y in range(avatar_size):
need_to_paint = need_color[x // block_size, y // block_size]
if need_to_paint:
draw.point((x, y), main_color)
,
img.show()
, - . , , , .
Let's fix this by adding a border of empty blocks.
for i in range(12):
need_color[0, i] = 0
need_color[11, i] = 0
need_color[i, 0] = 0
need_color[i, 11] = 0
Voila. Let's now take a look at the generated avatars for other nicknames.
And finally, especially for Habr.
That's all. Thanks to those who have finished reading, and those who want to experiment, I send them to my repository with all the code.