2013-11-26 21:23

Images embedded in HTML - Data URI Scheme

While working on the blog engine I found a technique for embedding images in the actual HTML file: Data URI Scheme, also known as RFC 2597.

This encoding scheme has been around for quite many years now and has been supported by a few browsers for some time, but unfortunately not by Internet Explorer 6 or 7 so it has been problematic to use. The usage of IE 6 and 7 is decreasing, and these versions are used by about 2-8% of all web surfers right now (there are different figures presented from different statistics providers). Surprisingly the usage of IE6 is larger than IE7.

I can live with not supporting IE6 any more.

So.. how is it done then? Quite simply with a specially crafted URL string.

This image: is created by this HTML image tag:

<img border="1" width="20" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCA
                                mU/z+zk0eQzluZux2MFIOUjNIPrBoKCWyToNYAAAAASUVORK5CYII=" />
It is the same PNG image used as background on this page. The src URL is the PNG image Base64 encoded and prefixed by the string data:image/png;base64,. It is allowed to break lines and have whitespace inside the Base64 string.

This encoding can be used in CSS as well, for example:

body {
  background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCA