Data URI scheme

The data URI scheme is a URI scheme (Uniform Resource Identifier scheme) that provides a way to include data in-line in web pages as if they were external resources. This technique allows normally separate elements such as images and style sheets to be fetched in a single HTTP request rather than multiple HTTP requests, which can be more efficient.

In browsers that fully support Data URIs for “navigation”, JavasSript generated content can be provided as file “download” to the user, simply by setting window.location.href to a Data URI. One example is the conversion of HTML tables to downloadable CSV using a Data URI like this: ‘data:text/csv;charset=UTF-8,’ + encodeURIComponent(csv), where “csv” has been generated by JavaScript.

Format

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

The encoding is indicated by ;base64. If it’s present the data is encoded as base64. Without it the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard %xx hex encoding of URLs for octets outside that range. If <MIME-type> is omitted, it defaults totext/plain;charset=US-ASCII. (As a shorthand, the type can be omitted but the charset parameter supplied.)

Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset’s specification must precede the base64 token.

Examples

HTML

An HTML fragment embedding a picture of small red dot: Red-dot-5px.png

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

As demonstrated above, data URIs encoded with base64 may contain whitespace for readability.

CSS

A CSS rule that includes a background image:

ul.checklist li.complete {
    padding-left: 20px;
    background: white url('data:image/png;base64,iVBORw0KGgoAA
AANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0l
EQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6
P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC') no-repeat scroll left top;
}

In Mozilla Firefox 5Google Chrome 17, and IE 9 (released June, 2011), encoded data must not contain newlines.

Because user agents must ignore a declaration with an unknown property,[10] a fallback to a regular url is possible using standard CSS:

div.menu {
    background-image: url('elephant.png');
    background-image: url('data:image/png;base64,iVBORw0KGgoAA
AANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0l
EQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6
P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC');
}

JavaScript

JavaScript statement that opens an embedded subwindow, as for a footnote link:

window.open('data:text/html;charset=utf-8,' + 
    encodeURIComponent( // Escape for URL formatting
        '<!DOCTYPE html>'+
        '<html lang="en">'+
        '<head><title>Embedded Window</title></head>'+
        '<body><h1>42</h1></body>'+
        '</html>'
    )
);

This example does not work with Internet Explorer 8 due to its security restrictions that prevent navigable file types from being used.[4]

Inclusion in HTML or CSS using PHP

Because base64-encoded data URIs are not human readable, a website author might prefer the encoded data be included in the page via a scripting language such as PHP. This has the advantage that if the included file changes, no modifications need to be made to the HTML file, and also of keeping a separation between binary data and text based formats. Disadvantages include greater server CPU use unless a server-side cache is used.

<?php
function data_uri($file, $mime) {
    $contents = file_get_contents($file);
    $base64 = base64_encode($contents);
    return "data:$mime;base64,$base64";
}
?>

<img src="<?php echo data_uri('elephant.png', 'image/png');
?>" alt="An elephant">

Similarly, if CSS is processed by PHP, the below function may also be used:

<?php header('Content-type: text/css'); ?>

div.menu {
    background-image:url('<?php echo data_uri('elephant.png',
    'image/png'); ?>');
}

Python

data_uri = open("sample.png", "rb").read().encode("base64").replace("\n", "")
img_tag = '<img alt="sample" src="data:image/png;base64,{0}">'.format(data_uri)
print img_tag

Python 3

import base64
data_uri = str(base64.encodestring(open("sample.png", "rb").read()) , "utf8").replace("\n", "")
img_tag = '<img alt="sample" src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)

Ruby 1.9.3

require "base64"
data_uri = Base64.encode64(File.open("sample.png", "rb").read).gsub(/\n/, "")
image_tag = '<img alt="sample" src="data:image/png;base64,%s">' % data_uri
puts image_tag

Perl

use MIME::Base64 qw(encode_base64);

open FH, '<', 'sample.png';
read(FH, $contents, 10000000);
$base64_data = encode_base64($contents, "");

print '<img alt="sample" src="data:image/png;base64,' . $base64_data . '">';

JavaScript (node.js)

var fs = require('fs');
var base64_data = fs.readFileSync('sample.png').toString('base64');
console.log('<img alt="sample" src="data:image/png;base64,' + base64_data + '">');

See also

  • MHTML, an alternative for attaching resources to an HTML document usually found in HTML email messages
  • MIME for the used mediatypes

One Reply to “Data URI scheme”

  1. This article is very interesting but it took me a long time to find it in google.
    I found it on 17 spot, you should focus on quality
    backlinks building, it will help you to rank to
    google top 10. And i know how to help you, just type in google – k2 seo tips

Leave a Reply