Skip to content

Instantly share code, notes, and snippets.

@mrinalwadhwa
Created June 19, 2012 01:34
Show Gist options
  • Save mrinalwadhwa/2951818 to your computer and use it in GitHub Desktop.
Save mrinalwadhwa/2951818 to your computer and use it in GitHub Desktop.
convert to data uri
# tools.ietf.org/html/rfc2397
# developer.mozilla.org/en/data_URIs
require 'base64'
require 'cgi'
# based on segment7.net/projects/ruby/datafy
def to_datauri(content, content_type)
outuri = 'data:' + content_type
unless content_type =~ /^text/i # base64 encode if not text
# content type anything other than text/*
# the URI is built like this:
# "data:" + content type + ";base64," + base64-encoded content
outuri += ';base64'
content = Base64.encode64(content).gsub("\n", '')
else
# if content type is text/*, the URI is built like this:
# "data:" + content type + "," + URL-encoded content
content = CGI.escape(content)
end
outuri += ",#{content}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment