Data URIs: Aren't They Pretty?
April 17th, 2007
While reading an article on digg.com about custom themes for Google Reader. I became curious about where they stored the images for the altered theme, so I began to investigate. I found that all of the images were base64 encoded in the CSS file for the theme. It made me think of some code I wrote in Javascript, some time ago, that would allow a person to load an image file in the browser using a standard file selection widget and would produce a base64 encoded string representing that image. It is extremely easy to do, but I figured I would put the code out there because it took me a while to figure it out.
Data URIs have been around for a while. When I was writing this code I had to to a bit of research to understand the positive or negative impact they would have on the project I was working on.
Please be aware that this code is FIREFOX ONLY. So with out further a due, here is the code:
Image.to_base64 = function(srcURL){
var canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "html:canvas");
canvas.width = canvas.height = 16;
var image = document.createElementNS("http://www.w3.org/1999/xhtml", "html:img");
image.src = srcURL;
var ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, 16, 16);
return canvas.toDataURL();
};
But wait before you run off and begin to use this code. There are some major limitations to data URIs. At first glance they seem like the panacea, but once you take a look at portability, performance and size they quickly fall short. Check out this Wikipedia definition. It was very helpful.
6699 Responses to “Data URIs: Aren't They Pretty? ”
Sorry, comments are closed for this article.