Skip to content

Instantly share code, notes, and snippets.

@rmax
Created March 29, 2011 19:46
Show Gist options
  • Save rmax/893081 to your computer and use it in GitHub Desktop.
Save rmax/893081 to your computer and use it in GitHub Desktop.
single script to convert a image into data uri
#!/usr/bin/env python
"""
Simple script to convert a image into data uri.
More info http://en.wikipedia.org/wiki/Data_URI_scheme
"""
import base64
import mimetypes
import sys
__author__ = "Rolando Espinoza La fuente <[email protected]>"
URI = "data:%sbase64,%s"
def get_data_uri(fname):
"""Outputs data uri for given files"""
value, _ = mimetypes.guess_type(fname)
mimetype = value + ";" if value else ""
data = ''.join(base64.encodestring(open(fname, "rb").read()).splitlines())
return URI % (mimetype, data)
if __name__ == '__main__':
try:
sys.stdout.write(get_data_uri(sys.argv[1]))
sys.stdout.write("\n")
except IndexError:
sys.stderr.write("File required\n")
else:
sys.exit(0)
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment