Created
January 21, 2016 12:30
-
-
Save Giacom/75bab479590f4f7bb364 to your computer and use it in GitHub Desktop.
Compiles a list of images, with the same width and height, into a single spritesheet.
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
| from PIL import Image | |
| from tqdm import tqdm | |
| import argparse | |
| import math | |
| # Constants for bounding boxes | |
| left = 0 | |
| top = 1 | |
| right = 2 | |
| bottom = 3 | |
| def main(): | |
| parser = argparse.ArgumentParser(description = 'Compile images together into a spritesheet.') | |
| parser.add_argument("files", nargs='+', help = "The files to compile together into a spritesheet. (E.g: myFile.png, *.png, myFile1.png myFile2.png)") | |
| parser.add_argument("-o", "--output", help = "The path to save the new spritesheet in.") | |
| parser.add_argument("-r", "--rows", help = "Limits how many rows the script must use.") | |
| cmdArgs = parser.parse_args() | |
| add_images(cmdArgs.files, cmdArgs.output, cmdArgs.rows) | |
| def add_images(files, output, rows): | |
| if output == None: | |
| output = "spritesheet_" + files[0] | |
| image_count = len(files) | |
| image_size_each = Image.open(files[0]).getbbox() | |
| image_width = image_size_each[right] | |
| image_height = image_size_each[bottom] | |
| image_rows = int(math.ceil(math.sqrt(image_count))) | |
| if rows != None: | |
| image_rows = int(rows) | |
| image_columns = int(math.ceil(float(image_count) / float(image_rows))) | |
| new_image = Image.new("RGBA", (image_width * image_columns, image_height * image_rows), (255, 255, 255, 0)) | |
| x = 0 | |
| y = 0 | |
| errorFiles = [] | |
| for file in tqdm(files, leave = True): | |
| try: | |
| image = Image.open(file) | |
| except IOError: | |
| errorFiles.append(file) | |
| continue | |
| new_image.paste(image, (image_size_each[right] * x, image_size_each[bottom] * y)) | |
| x += 1 | |
| if x == image_columns: | |
| x = 0 | |
| y += 1 | |
| if len(errorFiles) > 0: | |
| print "Unable to parse the following file(s):" | |
| for file in errorFiles: | |
| print '\t' + file | |
| new_image.save(output) | |
| print "Processing successful! New spritesheet saved to " + output | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment