mar
2
3
Data URIs
I’m guessing that a lot of web developers don’t know about data URIs. Most probably won’t even have to know about them. However, I still want to go over them because I think they are clever and could prove useful. The main advantage I see is the possibility to avoid an HTTP Request, especially for a small image.
Wikipedia’s overview is quite thorough. The article also links to a number of places where you can quickly throw together some data URI’s for any mime type. The most well known is the data URI kitchen.
Quickly, the format of a data URI is as follows:
Note that almost every section is optional! The mime type option means you can do some very interesting things. The normal usage might be to to embed a small image, as a datauri, inside the html document. However, another usage might be to embed an entire HTML document inside a link!
I was looking at the code for some command line utilities that make datauri’s and I learned an easy way to find out the mime type of a file is to use the `file` command:
So using `file –mime` and reading whats after the ‘: ‘ you can easily get a mime-type for any file. Then reading and base64 encoding the content you have a quick hack to quickly create datauris! Here goes:
#!/usr/bin/env ruby
# Quick & Dirty data URI for a file
#
# Filename and Contents
filename = ARGV[0]
contents = File.read(filename)
base64 = Base64.encode64(contents).gsub("\n",'')
# Mime Type for the Filename
output = `file --mime `
mime = output.match( /: (.*)$/ )[1].downcase.gsub(/\s/,'')
# Make Data URI
datauri = "data:;base64,"
# Output
puts datauri
Some better scripts are available. Here is a Perl implementation and a pretty neat Ruby Implementation.


Add a Comment