Data URIs and Inline Images


Jump to: navigation, search
Tip: This is part of the Weekly Web Hack article series. If you like it, please subscribe to my blog. Thanks!

Update: It turns out this does not work in Internet Explorer. I am currently investigating an IE specific alternative, which I plan to reveal in an upcoming Weekly Web Hack article.

In this edition of the Weekly Web Hack, I'll explain how data URIs work and give some practical examples when you might want to use them in your own project.

By the end of this article, you should be able to:

  1. Determine whether a particular use-case is suitable for inline data,
  2. Understand the data: URI scheme and available encodings,
  3. Use data URIs to embed image (and other) data directly into an HTML or CSS file.

Why use data URIs?

Here are some good litmus tests to help you decide if your use-case warrants using data URIs for inline images:

  • Are your images small? (think icon-sized -or- a few Kb at most)
  • Are your images fairly static? That is, are they unlikely to frequently change?
  • Are you using images as backgrounds for CSS classes?
  • Are your images presentationally relevant? (ex: rounded corners)
  • Does your site have high-throughput (bandwidth), but also high latency?

If you find yourself answering "yes" to the questions above, you may want to consider inlining your data. Inline images do not suffer the overhead of an HTTP round trip for the browser to retrieve them. This is especially useful for HTTPS connections, which require additional connection overhead - exaggerating any latency problems.

Also, since they are embedded directly into the page (either HTML or CSS), the image data is present at DOM render time. This means you won't see the all-too-common image flicker that occurs between DOM load and image load. However, the trade-off is that this will make the initial download time for the HTML or CSS that much longer. Using CSS as the storage location for the inline images rather than HTML will help mitigate this for subsequent page-loads since browsers tend to cache CSS files rather aggressively.

For further reading, see the wikipedia entry on the data: URI scheme. It has an excellent list of the technical advantages and disadvantages of using data URIs.

Data URI quick overview

Data URIs are dead simple. An easy way to think of them is by analogy - while a http URL points to content, a data URI actually contains the content.

A data URI follows this format:


Where <MIME-type> represents the Internet media type of the data. Examples include text/html, image/png and application/pdf. Though data URIs are not generally very popular, when they are employed they are most commonly used for embedding images.

The data can be encoded using either standard URL percent encoding, or using base64 encoding. If the optional ";base64" does not appear in the data URI, percent encoding is assumed.

A simple example

The following URL points to this image of a blueish "page copy" icon (Image:Page copy.png):

Note: Image courtesy of Mark James' fabulous Silk Icons

Here's the equivalent data URI using base64 encoding:


And here it is again, using regular URL percent encoding:


Notice that the percent encoded version is quite a bit larger. This will be heavily dependent on the type of data being encoded. Both base64 encoding and percent encoding will be larger than the original data size. Base64 encoded data is consistently about 35% larger than the original data, whereas percent encoding could be as little as 0% or as much as 200% larger depending on the data. For binary formats such as images, base64 will almost always result in a smaller output than percent encoding.

Usage in HTML

To use a data URI in an HTML file, simply inject it in the src attribute of a tag such as <img> or <iframe>. Continuing with the copy example, your HTML might look like the following:

<img alt="copy" src="data:image/png;base64,
    ...truncated for readability...
" />

Newlines in the URI are generally ignored, so insert breaking newlines wherever you feel is appropriate. In the above examples, the input has been truncated to 120 characters per line.

Usage in CSS

Using data URIs in CSS files is nearly the same as in HTML. Continuing the above example, you might have:

.copy {
  background: url(data:image/png;base64,
    ...truncated again for readability...

Converting files to base64 encoded data

Here's a simple PHP script to help you convert your files to either base64 or percent encoded strings:

if ($_FILES && $_FILES['uploadfile']) {
    header( "Content-type: text/plain; charset=UTF-8" );
    $fp = fopen( $_FILES['uploadfile']['tmp_name'], 'rb' );
    if ($_POST['base64']) {
        while (!feof($fp)) echo(base64_encode(fread($fp, 45))."\n");
    } else {
        $buf = '';
        while (!feof($fp)) {
            $buf .= rawurlencode(fread($fp, 120));
            while (strlen($buf)>=60) {
                $buf = substr($buf,60);
        if ($buf) echo($buf);
<title>Base64 File Encoder</title>
<form action="" method="post" enctype="multipart/form-data">
<p><label>File to convert: <input type="file" name="uploadfile" /></label>
<p><label>Check here to use base64 encoding: <input type="checkbox" name="base64" checked="checked" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>

Copy the above to a file called encode.php and host it on your own private server (localhost is fine). When you access the page, it will show you an upload form where you can post your files and get back the encoded data.

Enjoy! As always I'll be happy to answer any questions.

Got something to say?

Leave a comment
Sorry, comments are disabled.

or, read what others have said...