HTML & CSS embeded images. PHP example available.

Sometimes it is important to show the images very fast, even before all content is fully loaded. In this cases it is possible to embed images into HTML or CSS. While this approach can help in certain situations, it is very important always to remember limitations. Most important of them are:

  • URL length handled by the browsers is limited. it is 2k for Internet Explorer.
  • Base64 encoding of the string is about 33% bigger than the original string.
  • Never forget to cache the images as constant string encoding can waste quite a lot of your server CPU.

Here is simple HTML examle:

<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

Here is an image embeded into CSS:

div.image {
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);

Here is some sample PHP script that encodes the image into base64 encoding and embeds it into HTML.

function data_uri($file, $mime) {
    $contents = file_get_contents($file);
    $base64 = base64_encode($contents);
    return "data:$mime;base64,$base64";
<img alt="An elephant" src="%3C?php%20echo%20data_uri%28%27elephant.png%27,%20%27image/png%27%29;%0A?%3E" />

In one of the latest articles I am planning to provide more complicated example of embedded images usage, so follow me on twitter

Posted by:
Enjoyed this post? Share and Leave a comment below, thanks! :)