Created
February 24, 2020 00:44
-
-
Save jefersondaniel/5724c9e499dd4712e0c2e79eb56e1d89 to your computer and use it in GitHub Desktop.
Convert SVG to Android Drawables PNGs
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
#!/usr/bin/env python3 | |
import sys | |
import tempfile | |
import os | |
import argparse | |
import re | |
parser = argparse.ArgumentParser(description='Generate png icons from svg') | |
parser.add_argument('input_file', nargs=1, help='Input svg file') | |
parser.add_argument('output_directory', nargs=1, help='Drawable directory') | |
parser.add_argument('prefix', nargs=1, help='Drawable prefix') | |
parser.add_argument('--size', nargs='?', help='Size', const=1, type=int, default=48) | |
parser.add_argument('--fillcolor', nargs='?', help='Fill color', const=1, type=str, default='#ffffff') | |
args = parser.parse_args() | |
input_file = args.input_file[0] | |
output_directory = args.output_directory[0] | |
aux_file = tempfile.mkstemp(suffix='.svg')[1] | |
prefix = args.prefix[0] | |
fillcolor = args.fillcolor | |
base_size = float(args.size) | |
base_size_dpi = 'hdpi' | |
dpi_map = { | |
'ldpi': 120.0, | |
'mdpi': 160.0, | |
'hdpi': 240.0, | |
'xhdpi': 320.0, | |
'xxhdpi': 480.0, | |
'xxxhdpi': 640.0 | |
} | |
os.system('sed -e "s/<path/<path style=\\\"fill:{}\\\"/i" {} > {}'.format(fillcolor, input_file, aux_file)) | |
for dpi, value in dpi_map.items(): | |
ratio = value / dpi_map[base_size_dpi] | |
size = round(base_size * ratio) | |
name = re.sub(r'[^a-zA-Z0-9.]', '_', '{}{}.png'.format(prefix, os.path.basename(input_file.split('.')[0]))) | |
subdir = 'drawable-{}'.format(dpi) | |
destination_path = os.path.join(output_directory, subdir, name) | |
if not os.path.isdir(os.path.dirname(destination_path)): | |
os.makedirs(os.path.dirname(destination_path)) | |
os.system('inkscape -z -e {} -w {} -h {} {} > /dev/null 2>&1'.format(destination_path, size, size, aux_file)) | |
os.unlink(aux_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment