Clever PHP Tip: Encode & Decode Data URLs

Converting small images to data-URLs is a great way to eliminate HTTP requests and decrease loading time for your pages. Using PHP‘s base64_encode() and base64_decode() functions, we have the power to convert images to data-URLs and vice-versa.

This only makes sense for small images, such as those used on this blog for bullet lists: a good example of this is on this site's Archives page. Here the length of the code generated by the encoding is actually shorter than the url of the image, meaning the resulting css file is smaller—and the saving from the HTTP request we no longer need is correspondingly greater, indeed in this case much greater.

I've implemented this for my blog, but I chose to simply replace the url attribute for the background image property in my bulleted list styles:

.bullet-list li,.rollover-list li {
    background-image: url(/images/icons/bullets/bulleted-rollover-list/list-off.gif)
}

by the equivalent code rather than use a PHP file instead of CSS as described in the Perishable Press article:

.bullet-list li,.rollover-list li {
    background-image: url(data:image/jpg;
base64,R0lGODlhBQAFAIAAAJmZmQAAACH5BAkAAAEALAAAAAAFAAUAAAIEhI pWAA7)
}

If you really want to go the PHP route, see Chris Coyier's post (and resulting comments!) on ways of overcoming the drawbacks.