Created
November 4, 2013 10:42
-
-
Save dmr/7300883 to your computer and use it in GitHub Desktop.
The script accepts a glob pattern and prints the base64 encoded image on the commandline. Helpful to convert images to inline css
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
import base64 | |
import glob | |
import argparse | |
import os | |
# fmt_str = u"define(function(){{return 'data:{mimetype};base64,{content}';}});" | |
fmt_str = u'"data:{mimetype};base64,{content}"' | |
ft_map = { | |
'.jpg': 'image/jpg', | |
'.jpeg': 'image/jpg', | |
'.png': 'image/png' | |
} | |
def fn_or_pattern_to_b64(fn_or_pattern, debug=False, fmt_template=fmt_str): | |
for fn in glob.glob(fn_or_pattern): | |
ext = os.path.splitext(fn) | |
if ext[1].lower() not in ft_map.keys(): | |
raise Exception("Error processing file '{0}'. Only jpg, jpeg and png supported, sry :)".format(fn)) | |
mimetype = ft_map[ext[1].lower()] | |
with open(fn) as fp: | |
content = base64.b64encode(fp.read()) | |
content_result = fmt_template.format(mimetype=mimetype, content=content) | |
if debug: | |
print u'##### {0}'.format(fn) | |
print content_result | |
# with open(fn+u'.js', 'wb') as fp: fp.write(content_result) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Pass filenames or glob patterns and the base64 encoded content will be printed on the commandline') | |
parser.add_argument( | |
'fn_or_pattern', metavar='filename', type=str, nargs='+', help='Filename or glob pattern') | |
for fn_or_pattern in parser.parse_args().fn_or_pattern: | |
fn_or_pattern_to_b64(fn_or_pattern=fn_or_pattern, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment