Skip to content

Instantly share code, notes, and snippets.

@jlongman
Forked from josephsu/gist:4481205
Last active August 9, 2017 18:24
Show Gist options
  • Save jlongman/d8bab076078b83f84e299d770adc07b7 to your computer and use it in GitHub Desktop.
Save jlongman/d8bab076078b83f84e299d770adc07b7 to your computer and use it in GitHub Desktop.
decode Data URI to mime and data parts
#!/usr/bin/env python
# Convert a data uri file into the data part
#
# Usage: daturi.py infile
#
# Copy a response from Chrome
# pbaste > foo
# daturi.py foo
# creates foo.mimetype
import base64
import sys
def decodeDataUri(uristr):
comma = uristr.find(',')
urihead = uristr.find('data:')
if urihead is None or comma is None:
return None
headpart = uristr[urihead + 5:comma]
firstsep = headpart.find(';')
if firstsep is None:
firstsep = len(firstsep)
mimetype = headpart[0:firstsep]
b64data = uristr[(comma + 1):]
rawdata = base64.b64decode(b64data)
return ( mimetype, rawdata )
with open(sys.argv[1], 'r') as my_file:
mime, data = decodeDataUri(my_file.read())
mime = mime.replace('/', '.')
with open(sys.argv[1] + "." + mime, 'wb') as out_file:
out_file.write(data);
@jlongman
Copy link
Author

jlongman commented Aug 9, 2017

This can be adapted into a Service on MacOS but it isn't especially satisfying if you're trying to get it direct from the browser.

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