Skip to content

Instantly share code, notes, and snippets.

@samthor
Last active August 29, 2015 14:20
Show Gist options
  • Save samthor/0d389da4c4f0596c2e26 to your computer and use it in GitHub Desktop.
Save samthor/0d389da4c4f0596c2e26 to your computer and use it in GitHub Desktop.
renders svg or other images to mobile device sizes
#!/usr/bin/env python
import os
import sys
SCALES = {
1: ['mdpi/', ''],
1.5: ['hdpi/'],
2: ['xxdpi/', '@2x'],
3: ['xxhdpi/', '@3x'],
}
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--size', '-s', type=int, required=True,
help='base 1x size to generate')
parser.add_argument('--out', '-o', type=str, default='.',
help='path to output to')
parser.add_argument('--crush', '-p', action='store_true',
help='whether to pngcrush')
parser.add_argument('files', type=str, nargs='+',
help='image files to render')
args = parser.parse_args()
if args.size <= 16:
sys.stderr.write('warning: Quick Look seems to ignore sizes <= 16px\n')
sys.stderr.write('\n')
# Move to output folder, create Android output paths.
cwd = os.getcwd()
try:
os.mkdir(args.out)
except:
pass # ignore
os.chdir(args.out)
for _, outs in SCALES.items():
for approach in outs:
if approach.endswith('/') and not os.path.isdir(approach):
os.mkdir(approach)
# Enumerate and render files on Mac OS X.
for path in args.files:
name, ext = os.path.splitext(path)
in_path = os.path.join(cwd, path)
out_path = '{}{}.png'.format(os.path.basename(name), ext)
print(name)
sys.stderr.write('using out_path={}\n'.format(out_path))
# Render each file at the right scale.
for scale, outs in SCALES.items():
size = int(args.size * scale)
os.system('qlmanage -t -s {} -o . {} >/dev/null 2>&1'.format(size, in_path))
print('>> {}'.format(size))
# pngcrush if requested
if args.crush:
os.system('pngcrush -ow {} >/dev/null'.format(out_path))
# Link into multiple approaches.
for approach in outs:
if approach.endswith('/'):
cname = approach + name + '.png'
else:
cname = name + approach + '.png'
os.link(out_path, cname)
os.unlink(out_path)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment