Using base64 encoded data URI images
comments (2) Views: 10,380
While working on a recent open source project that I released called CFDirectoryLister I had a choice to make. The goal was to have something that could be dropped into a directory and it would just work. The problem was that I wanted an attractive solution for developers, but I didn't want a lot of dependencies like icons, or external stylesheets.
The solution was to use data URI schemes. Rather than a traditional URL that points to a file on a filesystem somewhere, you provide a base64 encoded version of your file, prepended with a command indicating the mime type of the following data, and it's encoding type. The basics look something like this:
<img src="data:image/jpeg;base64,<encoded-characters> />
The goal of this approach isn't to save bandwidth so much as it is to reduce HTTP requests. In some cases converting an image to base64 actually increases the total size. You can use a base64 encoded image anywhere you'd use a normal image, including in your CSS. It's actually fairly simply to one-off encode images using Terminal for your Mac. I've included a few commands which can be issued from Terminal, along with the resulting output. The | pbcopy tacked on to the end of each command causes the output of the encoding to be copied to the Mac's clipboard. Each of these options also allow the results to be written to a file if you prefer to go that route.
python -c 'print open("me.png", "rb").read().encode("base64").replace(" ","")' | pbcopy
openssl base64 < me.png | tr -d ' ' | pbcopy
base64 -i me.png | pbcopy
Of course encoding from the command line isn't always the best solution. Every modern programming language offers their own encoding options and ColdFusion is no different. Here's a few options for base64 encoding with ColdFusion:
<cfimage name="myPic" action="read" source="/path/to/picture.jpg"> <img src="data:image/*;base64,#toBase64( myPic )#" />
<cfset myPic = fileReadBinary(expandPath( "/path/to/picture.jpg" ))> <img src="data:image/*;base64,#toBase64( myPic )#" />
Of course you're not going to want to encode those every time so if this is your approach, do it once then store it somewhere first. This might also be a good option for emails too. It might help avoid having to load in images, which means your users might see the images rather than be asked to load them. Your mileage may vary so make sure to test before sending large mailings. Good luk and have fun.
If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!