Data URLs are a useful feature introduced in the web scenario during the last years. Using this feature, we can include small graphics (only up to 32 Kb in size) in our web documents. This kind of URLs have the syntax data:content-type;base64,encoded-data
, where content-type
is the mime type of our resource (e.g. image/gif
) and encoded-data
is a Base-64 encoded string containing our resource. You can use these URLs on all HTML elements that accept external content, such as a
, object
and, of course, img
. Here's an example:
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
If you enter the above data URL in the address bar of your browser and press Enter, you will actually see the image contained in such URL.
We can benefit from data URLs by using a server-side language (such as PHP) to encode our resources into Base64 and return them through AJAX so that we can use them in our web pages. First of all, we need to set up the server-side script:
<?php $file = file_get_contents('image.gif'); $encoded = base64_encode($file); echo $encoded; ?>
As you can see, we used the base64_encode()
function of PHP to get a Base64 encoded string containing our image. Now we can use jQuery:
$('<img/>').insertAfter('p:first').hide(); var base = 'data:image/gif;base64,'; $('#run').click(function(e) { $.ajax({ type: 'GET', url: 'script.php', data: null, success: function(data) { var url = base + data; $('p:first').next().attr('src', url).show(); } }); e.preventDefault(); });
We've first inserted a blank image into the page and then hidden it. Then we've prepared our URL that will be completed by the data fetched with AJAX. Finally, we've set the src
attribute of our image to our data URL and shown the image itself. You can see a demo below.