Created
August 27, 2011 09:01
-
-
Save japboy/1175164 to your computer and use it in GitHub Desktop.
Data URI Converter
This file contains 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 | |
# -*- coding: utf-8 -*- | |
import os | |
import sys | |
import base64 | |
import mimetypes | |
import gtk | |
def get_mimetype_string(file_path): | |
file_types = mimetypes.guess_type(file_path, False) | |
return file_types[0] | |
def get_file_string(file_path): | |
f = open(file_path, 'r') | |
file_string = f.read() | |
f.close | |
return file_string | |
def get_b64_string(file_string): | |
b64_string = base64.b64encode(file_string) | |
return b64_string | |
def get_data_uri(mimetype_string, b64_file_string): | |
return 'data:' + mimetype_string + ';base64,' + b64_file_string | |
def copy_to_clipboard(data_string): | |
cb = gtk.clipboard_get() | |
cb.set_text(data_string) | |
cb.store() | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: | |
sys.stderr.write('Invalid argument(s)\n') | |
sys.exit(2) | |
file_path = sys.argv[1] | |
if not os.path.isfile(file_path): | |
sys.stderr.write('Invalid file path\n') | |
sys.exit(2) | |
file_path = sys.argv[1] | |
file_type = get_mimetype_string(file_path) | |
file_string = get_file_string(file_path) | |
b64_string = get_b64_string(file_string) | |
data_uri = get_data_uri(file_type, b64_string) | |
copy_to_clipboard(data_uri) | |
sys.stdout.write(data_uri + '\n'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment