Created
January 20, 2012 18:46
-
-
Save philippbosch/1648953 to your computer and use it in GitHub Desktop.
Command line tool to convert arbitrary files to data: URIs.
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 python | |
# encoding: utf-8 | |
import getopt | |
import magic | |
import sys | |
help_message = ''' | |
Convert arbitrary files to data: URIs. | |
Usage: | |
todatauri.py <filename> | |
''' | |
class Usage(Exception): | |
def __init__(self, msg): | |
self.msg = msg | |
def main(): | |
try: | |
if len(sys.argv) != 2: | |
raise Usage(help_message) | |
f = open(sys.argv[1]) | |
contents = f.read() | |
contents_encoded = contents.encode('base64').replace('\n','') | |
mime = magic.Magic(mime=True) | |
mime_type = mime.from_buffer(contents) | |
data_uri = 'data:%s;base64,%s' % (mime_type, contents_encoded) | |
print data_uri | |
except Usage, err: | |
print >> sys.stderr, str(err.msg) | |
return 2 | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment