identiconGeneration.py.bak
1 """ 2 Core classes for loading images and converting them to a Texture. 3 The raw image data can be keep in memory for further access 4 """ 5 import hashlib 6 from io import BytesIO 7 8 from PIL import Image 9 from kivy.core.image import Image as CoreImage 10 from kivy.uix.image import Image as kiImage 11 12 13 # constants 14 RESOLUTION = 300, 300 15 V_RESOLUTION = 7, 7 16 BACKGROUND_COLOR = 255, 255, 255, 255 17 MODE = "RGB" 18 19 20 def generate(Generate_string=None): 21 """Generating string""" 22 hash_string = generate_hash(Generate_string) 23 color = random_color(hash_string) 24 image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR) 25 image = generate_image(image, color, hash_string) 26 image = image.resize(RESOLUTION, 0) 27 data = BytesIO() 28 image.save(data, format='png') 29 data.seek(0) 30 # yes you actually need this 31 im = CoreImage(BytesIO(data.read()), ext='png') 32 beeld = kiImage() 33 # only use this line in first code instance 34 beeld.texture = im.texture 35 return beeld 36 37 38 def generate_hash(string): 39 """Generating hash""" 40 try: 41 # make input case insensitive 42 string = str.lower(string) 43 hash_object = hashlib.md5( # nosec B324, B303 44 str.encode(string)) 45 print(hash_object.hexdigest()) 46 # returned object is a hex string 47 return hash_object.hexdigest() 48 except IndexError: 49 print("Error: Please enter a string as an argument.") 50 51 52 def random_color(hash_string): 53 """Getting random color""" 54 # remove first three digits from hex string 55 split = 6 56 rgb = hash_string[:split] 57 split = 2 58 r = rgb[:split] 59 g = rgb[split:2 * split] 60 b = rgb[2 * split:3 * split] 61 color = (int(r, 16), int(g, 16), int(b, 16), 0xFF) 62 return color 63 64 65 def generate_image(image, color, hash_string): 66 """Generating images""" 67 hash_string = hash_string[6:] 68 lower_x = 1 69 lower_y = 1 70 upper_x = int(V_RESOLUTION[0] / 2) + 1 71 upper_y = V_RESOLUTION[1] - 1 72 limit_x = V_RESOLUTION[0] - 1 73 index = 0 74 for x in range(lower_x, upper_x): 75 for y in range(lower_y, upper_y): 76 if int(hash_string[index], 16) % 2 == 0: 77 image.putpixel((x, y), color) 78 image.putpixel((limit_x - x, y), color) 79 index = index + 1 80 return image