Skip to content

Instantly share code, notes, and snippets.

Created July 18, 2011 14:48
  • Star 26 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jsocol/1089733 to your computer and use it in GitHub Desktop.
Give an image, get a data-uri
#!/usr/bin/env python
"""Command line script to convert a file, usually an image, into a data URI
for use on the web."""
import base64
import mimetypes
import os
import sys
class FileNotFoundError(Exception):
def img_to_data(path):
"""Convert a file (specified by a path) into a data URI."""
if not os.path.exists(path):
raise FileNotFoundError
mime, _ = mimetypes.guess_type(path)
with open(path, 'rb') as fp:
data =
data64 = u''.join(base64.encodestring(data).splitlines())
return u'data:%s;base64,%s' % (mime, data64)
def usage(argv):
print 'Usage: %s <path-to-file>' % argv[0]
if __name__ == '__main__':
path = sys.argv[1]
except IndexError:
print img_to_data(path)
except FileNotFoundError:
print 'File not found!'
Copy link

rik commented Jul 26, 2011

Thanks for this.

I use it with this command on Mac to copy the output in my clipboard:
data-uri file.img | pbpaste

Copy link

nice for server side compression

what do you think about this pure javascript version ?

Copy link

jsocol commented Aug 17, 2011

@revolunet: There are a number of websites/services that will do it, I specifically wanted something that didn't make me find one of them, or open a browser :)

Copy link

benmj commented May 15, 2013

This is rad. So simple yet so effective.

Copy link

Thanks a lot for this.

Copy link

jwlyn commented Apr 1, 2019

what about SVG? this don't work.

Copy link

how to use this

Copy link

@santosh-burada ....sorry for a reply a year

$ python3 path/to/image.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment