Created
June 19, 2012 01:34
-
-
Save mrinalwadhwa/2951818 to your computer and use it in GitHub Desktop.
convert to data uri
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
# 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