Created
March 19, 2019 07:08
-
-
Save dipu-bd/694cb42e257c494d1600fe342ef740c3 to your computer and use it in GitHub Desktop.
Generate an avatar image from hash of an string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import sys | |
import hashlib | |
import numpy as np | |
from PIL import Image | |
from random import randint | |
def generate(string): | |
# control variables | |
rows = 8 | |
cols = 8 | |
width = 256 | |
height = 256 | |
# generate hash | |
m = hashlib.shake_256() | |
m.update(string.encode()) | |
data = m.digest(rows * cols) | |
# create a bit-field | |
bits = [] | |
for n in data: | |
for i in range(8): | |
bits.append((n >> i) & 1) | |
# end for | |
# end for | |
# get a color for the image | |
colors = [ | |
[0, 0, 1], | |
[0, 1, 0], | |
[1, 0, 0], | |
] | |
cc = randint(0, len(colors) - 1) | |
# create an array | |
arr = np.ones((rows + 2, cols + 2, 3)) | |
for i in range(rows): | |
for j in range(cols): | |
n = bits[i * cols + j] | |
arr[i + 1, j + 1] = colors[cc] if n else [1, 1, 1] | |
# end for | |
# end for | |
# save image | |
arr = (arr * 255).astype(np.uint8) | |
image = Image.fromarray(arr) | |
image = image.resize((width, height), resample=Image.BOX) | |
image.save('image.bmp') | |
# end def | |
def main(): | |
if len(sys.argv) <= 1: | |
raise Exception('You should provide some strings to genrate images') | |
# end if | |
names = sys.argv[1:] | |
for name in names: | |
generate(name) | |
# end for | |
# end def | |
if __name__ == '__main__': | |
main() | |
# end if |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment