summaryrefslogtreecommitdiff
path: root/hemiptera_avatar_gen.py
blob: db380a95d2bf85ead250a7f0e4994b3f82bacc26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import hashlib
import random
from PIL import Image, ImageDraw
from hemiptera_common import *
import os

SERVER_SALT="foobar"

D = 7
pixel_width=1
def hash_generator(h) :
    index = 0
    while True :
        yield int(h[index],16)
        index +=1
        if index == len(h) : ## Keep images interesting if size is significantly larger than hash input
            index = 0
            h = hashlib.sha1(h.encode()).hexdigest()


def gen_color(h) :
    return  tuple(tuple(next(h)*16 for i in range(3)) for i in range(2))

def gen_image(h) :
    h = hash_generator(h)
    c1, c2 = gen_color(h)
    im = Image.new("RGBA", (D,D))
    draw = ImageDraw.Draw(im)
    index = 0
    for i in range(D//2+1) :
        for j in range(D) :
            k = next(h)
            if k % 2 or k//2 % 2 :
                if k % 2 :
                    color = c1
                else :
                    color = c2
                draw.point([(i,j), (D-1-i,j)], fill=color)
    return im


def generate_avatar(email) :
    if email is None :
        email = ""
    h = hashlib.sha1(str(email+SERVER_SALT).encode()).hexdigest()
    imgpath = opj(basedir, "export", "static")
    img = gen_image(h)
    os.makedirs(imgpath, exist_ok=True)
    img.save(opj(imgpath, h+".png"))
    return "/static/" + h+".png"