Last active
July 5, 2016 14:25
-
-
Save qdwang/262fbee273ce0ed34ef5 to your computer and use it in GitHub Desktop.
css sprite
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
#!/usr/bin/env python | |
import sys, os, time | |
import Image | |
curr_dir = ''.join(os.path.split(os.path.abspath(sys.argv[0]))[:-1]) | |
curr_files = [f for f in os.listdir(curr_dir) if os.path.isfile(os.path.join(curr_dir, f))] | |
surfixes = ['png', 'jpg', 'gif'] | |
pic_files = {} | |
save_name = 'sprite' | |
gap = 10 | |
vert_style = True | |
def makeSprite(pic_seq, pic_type): | |
widths = [seq.size[0] for seq in pic_seq] | |
heights = [seq.size[1] for seq in pic_seq] | |
if vert_style: | |
pic_width = max(widths) | |
pic_height = sum(heights) + (len(heights) - 1) * gap | |
else: | |
pic_height = max(heights) | |
pic_width = sum(widths) + (len(widths) - 1) * gap | |
new_img = Image.new('RGBA', (pic_width, pic_height)) | |
last_pos = (0, 0) | |
for p in pic_seq: | |
new_img.paste(p, (last_pos[0], last_pos[1], p.size[0] + last_pos[0], p.size[1] + last_pos[1])) | |
if vert_style: | |
last_pos = (last_pos[0], last_pos[1] + p.size[1] + gap) | |
else: | |
last_pos = (last_pos[0] + p.size[0] + gap, last_pos[1]) | |
mode_type = pic_type if pic_type != 'jpg' else 'jpeg' | |
new_img.save(os.path.join(curr_dir, save_name + '.' + pic_type), mode_type, quality=80) | |
if __name__ == '__main__': | |
for f in curr_files: | |
for s in surfixes: | |
if len(f) > 3 and s == f[-3:] and save_name not in f: | |
if (not pic_files.get(s)): | |
pic_files[s] = [Image.open(os.path.join(curr_dir, f))] | |
else: | |
pic_files[s].append(Image.open(os.path.join(curr_dir, f))) | |
pic_canvases = {} | |
for pic_type in pic_files: | |
pic_seq = [p for p in pic_files[pic_type]] | |
makeSprite(pic_seq, pic_type) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment