Created
July 16, 2018 04:27
-
-
Save jobliz/1dcace611733cf2243ba4ca70365e4e3 to your computer and use it in GitHub Desktop.
Create CSS spritesheet with mogrify and glue-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
import os | |
import sys | |
import atexit | |
import shutil | |
import subprocess | |
def main(width, height): | |
# get image paths in full | |
dir_path = os.path.dirname(os.path.realpath(__file__)) | |
dir_images = os.path.join(dir_path, 'sprite-src/') | |
image_filenames = os.listdir(dir_images) | |
image_fullpaths = [os.path.join(dir_images, i) for i in image_filenames] | |
build_destination = os.path.join(dir_path, 'src/assets/') | |
# create and aggregate black and white versions | |
bw_names = [] | |
bw_paths = [] | |
for name, path in zip(image_filenames, image_fullpaths): | |
splits = name.split('.') | |
bw_name = ''.join([splits[0], '_bw', '.', splits[1]]) | |
bw_path = os.path.join(dir_images, bw_name) | |
subprocess.call(['convert', path, '-colorspace', 'Gray', bw_path]) | |
bw_names.append(bw_name) | |
bw_paths.append(bw_path) | |
# register function to remove black and white images when script exists | |
def remove_bw_images(): | |
for path in bw_paths: | |
os.remove(path) | |
atexit.register(remove_bw_images) | |
# create a temp folder with centered images with same transparent padding | |
# also delete it at end of execution | |
tmp_mogrified = '/tmp/sprites-mogrified' | |
def remove_mogrified_images(): | |
try: | |
shutil.rmtree(tmp_mogrified) | |
except Exception: | |
pass | |
remove_mogrified_images() | |
os.mkdir(tmp_mogrified) | |
# atexit.register(remove_mogrified_images) | |
# mogrify images to same size and with transparency | |
# https://stackoverflow.com/questions/32466048/imagemagick-convert-crop-and-resize | |
size_string = ''.join([str(width), 'x', str(height)]) | |
subprocess.call(['mogrify', | |
'-resize', size_string, | |
'-extent', size_string, | |
'-background', 'transparent', | |
'-gravity', 'center', | |
'-format', 'png', | |
'-path', tmp_mogrified, | |
''.join([dir_images, '/', '*.png']) | |
]) | |
# create sprite image and unedited css file | |
subprocess.call(['glue-sprite', tmp_mogrified, build_destination]) | |
if __name__ == "__main__": | |
w = int(sys.argv[1]) | |
h = int(sys.argv[2]) | |
main(w, h) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment