Make sprites of images using Python and PIL
This file contains 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
|# This work is licensed under the Creative Commons Attribution 3.0 United|
|# States License. To view a copy of this license, visit|
|# http://creativecommons.org/licenses/by/3.0/us/ or send a letter to Creative|
|# Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.|
|# from http://oranlooney.com/make-css-sprites-python-image-library/|
|# Orignial Author Oran Looney <firstname.lastname@example.org>|
|#mods by Josh Gourneau <email@example.com> to make one big horizontal sprite JPG with no spaces between images|
|from PIL import Image|
|#get your images using glob|
|iconMap = glob.glob("images/*.jpg")|
|#just take the even ones|
|iconMap = sorted(iconMap)|
|#iconMap = iconMap[::2]|
|images = [Image.open(filename) for filename in iconMap]|
|print "%d images will be combined." % len(images)|
|image_width, image_height = images.size|
|print "all images assumed to be %d by %d." % (image_width, image_height)|
|master_width = (image_width * len(images) )|
|#seperate each image with lots of whitespace|
|master_height = image_height|
|print "the master image will by %d by %d" % (master_width, master_height)|
|print "creating image...",|
|master = Image.new(|
|color=(0,0,0,0)) # fully transparent|
|for count, image in enumerate(images):|
|location = image_width*count|
|print "adding %s at %d..." % (iconMap[count], location),|
|print "done adding icons."|
|print "saving master.jpg...",|
|master.save('master.jpg', transparency=0 )|
May 4, 2021
Thank you Joshua, after 10 years your example is still interesting.
For me worked fine I just had a compilation error (OSError: cannot write mode RGBA as JPEG) at the end saving the file.
I had to change master mode from RGBA to RGB and worked like a charm!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
wow thanks Joshua
i was looking for this because basic software or other application crash when i have to deal with larger file like 18k ox 200k image which i use for video spritesheet.
looking forward to use your code and mody it.