Skip to content

Instantly share code, notes, and snippets.

@philippbosch
Created January 20, 2012 18:46
Show Gist options
  • Save philippbosch/1648953 to your computer and use it in GitHub Desktop.
Save philippbosch/1648953 to your computer and use it in GitHub Desktop.
Command line tool to convert arbitrary files to data: URIs.
#!/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