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.

Decoding Data URL Images

So we start with a small image named, say, “baseball.gif”:

We then convert to data-URL format by encoding with base64_encode()1:

This will output the image as a string of base64-encoded gibberish, which I will not utter here. It begins and ends with these characters:


And just keeps going for about 4KB-worth of code, which is actually larger than the original image. But that’s okay because saving an extra HTTP request is better for performance than a few extra kilobytes of code. Now that we’ve encoded the image, we can display it in our web pages like so:

Or display in our dynamic CSS.php file:

Share on FacebookShare on Google+Email this to someoneShare on RedditShare on LinkedInShare on TumblrTweet about this on TwitterShare on StumbleUpon

Leave a Reply

Your email address will not be published.