Generating default Github avatars

In this article I will show and tell you how you can generate avatars like on Github.





Generation result for nickname "test1"
Generation result for nickname "test1"

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.





How many squares are in the avatar
How many squares are in the avatar

Each avatar has 12 by 12 blocks.





Random autark from the open spaces of Github
Random autark from the open spaces of Github

, , , 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 \ cdot 12 \ cdot 1 \ text {bit} = 72 \ text {bit} = 9 \ text {byte}
#   6  12
need_color = np.array([bit == '1' for byte in bytes[3:3+9for bit in bin(byte)[2:].zfill(8)]).reshape(612)

#   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()
      
      







Result

, - . , , , .





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.





test2
test2
test3
test3
test4
test4
test5
test5

And finally, especially for Habr.





habr
habr
ufo
ufo

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.








All Articles