-
-
Save 3l3gant-cod3s/6d5bab4b8f5c116e7b447538a8095a62 to your computer and use it in GitHub Desktop.
Give an image, get a data-uri
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/python3 | |
"""Command line script to convert a file, usually an image, into a data URI | |
for use in CSS (no return every 76 chars) """ | |
import base64 | |
import mimetypes | |
import os | |
import sys | |
class FileNotFoundError(Exception): | |
pass | |
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 = fp.read() | |
# ~ data64 = u''.join(map(chr, base64.encodebytes(data))) | |
data64 = u''.join(map(chr, base64.b64encode(data))) | |
return u'data:%s;base64,%s' % (mime, data64) | |
def usage(argv): | |
print('Usage: %s <path-to-file>' % argv[0]) | |
if __name__ == '__main__': | |
try: | |
path = sys.argv[1] | |
except IndexError: | |
usage(sys.argv) | |
sys.exit(1) | |
try: | |
print(img_to_data(path)) | |
except FileNotFoundError: | |
print('File not found!') | |
sys.exit(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment