TEMPLATE_PRIMARY = ''' {elements_top} {elements_left} {elements_right} {elements_top} {elements_left} {elements_right} ''' TEMPLATE_PIXEL = ''' ''' import os import PIL.Image import random import sys # These numbers are MAGIC, and only work because of how the template was made. SQUARE_WIDTH = 300 START_X = 194.94924 START_Y = 637.82417 def hexadecimal(i): i = hex(i)[2:] width = 2 - (len(i) % 2) if width == 2: width = 0 i = ('0'*width) + i return i def mirror(image, direction): new_image = image.copy() for y in range(image.size[1]): for x in range(image.size[0]): pixel = image.getpixel((x, y)) if direction == 'horizontal': x = (image.size[0] - 1) - x elif direction == 'vertical': y = (image.size[1] - 1) - y new_image.putpixel((x, y), pixel) return new_image def vectorize(filenames): images = [PIL.Image.open(f) for f in filenames] if len(images) == 1: images = [images[0], images[0], images[0]] elif len(images) == 2: images = [images[0], images[1], images[1]] elif len(images) == 3: pass else: raise ValueError('Invalid number of images supplied') images[0] = images[0].rotate(270) images[2] = mirror(images[2], 'horizontal') elements_total = [] for (image_index, image) in enumerate(images): elements_local = [] width = image.size[0] step = SQUARE_WIDTH / width pixsize = SQUARE_WIDTH / width for y in range(width): y_point = START_Y + (y * step) for x in range(width): x_point = START_X + (x * step) color = image.getpixel((x, y)) opacity = 1 if isinstance(color, int): color = hexadecimal(color) * 3 elif isinstance(color, tuple): if len(color) == 4: opacity = color[3] / 255 if len(color) >= 3: color = ''.join(hexadecimal(channel) for channel in color[:3]) element = TEMPLATE_PIXEL.format( x=x_point, y=y_point, opacity=opacity, pixsize=pixsize, color=color, id='face_%d_%d' % (image_index, x + (y*width))) elements_local.append(element) elements_total.append(elements_local) elements_total = [''.join(elements) for elements in elements_total] image = TEMPLATE_PRIMARY.format(elements_top=elements_total[0], elements_right=elements_total[1], elements_left=elements_total[2]) image = image.strip() basenames = [os.path.splitext(f)[0] for f in filenames] outputname = '+'.join(basenames) + '.svg' print(outputname) f = open(outputname, 'w') f.write(image) f.close() if __name__ == '__main__': filenames = sys.argv[1:] vectorize(filenames)