Image to data URI convertor
author: mike foskett incept: 28th January 2010
last modified: 29th April 2012
A simple utility to convert an image into base 64 data URIs for embedding images.
It's best practice to optimise images prior to conversion via a tool such as SmushIt, Image Optimizer or PunyPNG.
Embedded images should be stored in cacheable files such as flat, not dynamic, HTML and style sheets. Data URI style sheets should be cached long term, rename the file on each update.
Note: The file size increases by approximately 30% which may be offset by serving as part of a compressed (gzip / deflate) file. Take a look at this simple gzip content method.
Note: IEv8 has the lowest maximum data URI size of 32768 Bytes. Upload is limited to that maximum. Because of the approximate 30% increase in the conversion it is possible the result is larger than IEv8 can actually handle.
Note: base 64 data URI embedded images do not work in IE less than version 8. Personally I circumvent this issue by having one style sheet which contains image reference data for IEv6 & 7, and a second, served by a conditional comment, containing data URIs:
/* All browsers (contains image references for IEv6 & 7 via the star hack perhaps) */
<link rel="stylesheet" href="page.css" type="text/css" media="all" />
/* All non-IE browsers and IE > v7 see this: */
<!--[if gt IE 7]><!-->
<link rel="stylesheet" href="data_uri.css" type="text/css" media="all" />
<!--<![endif]-->
All layout definitions should be in "page.css" including a reference to the image for IE 6 & 7. Personally I use the star hack for this purpose:
.sprite {
*background-image:url(sprite.png); /* Only IEv6 & 7 see this */
background-position: 0 0;
background-repeat: no-repeat;
width: 10px;
height: 20px;
}
While in "data_uri.css" only the background image itself is referenced:
.sprite {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAA... etc );
}
Further reading:
- Inline Images with Data URLs
- data URI scheme
- Why The data: URI Scheme Could Help Save Your Slow Site
- Data URIs explained
- Detecting Support for data: URIs
- Using Data URIs in CSS
- Generic Data URI sprites
- CSS Trick: Data URIs
If you have any alternate resources why not email me?
