import glob from PIL import Image #Find all gifs which have an underscore in the middle and save the prefix names prefixes = set() for filename in glob.glob('*.gif'): name, _ = filename.split('.') if '_' in name: prefix, _ = name.split('_') prefixes.add(prefix) #The first element of the tuple is the position suffix #The second one is another tuple containing the column #and the row to which each position be pasted. #Example: fr1 (front 1) will be pasted into first row, first column #lf2 (left 2) will be pasted to column 1 row 3 (the fourth row) positions = [("fr1", (0, 0)), ("fr2", (1, 0)) , ("rt1", (0, 1)), ("rt2", (1, 1)), ("bk1", (0, 2)), ("bk2", (1, 2)), ("lf1", (0, 3)), ("lf2", (1, 3))] #For each prefix, create a new image with alpha channel for prefix in prefixes: sprite = Image.new('RGBA', (64, 128)) for position in positions: suffix, coord = position src_img = prefix + "_" + suffix + ".gif" img = Image.open(src_img) sprite.paste(img, (coord[0] * 32, coord[1] * 32)) #Change alpha value of white pixels to 0 #Snippet found at: #https://stackoverflow.com/questions/765736/how-to-use-pil-to-make-all-white-pixels-transparent pixdata = sprite.load() width, height = sprite.size for y in range(height): for x in range(width): if pixdata[x, y] == (255, 255, 255, 255): pixdata[x, y] = (255, 255, 255, 0) #save sprite sprite.save(prefix + ".png", "PNG")