Create Data URI’s

These can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at the cost of maintainability. More information. There are online tools to do it, but if you want your own very simple utility, here's some PHP to do it:

function data_uri($file, $mime) {
  echo "data:$mime;base64,$base64";


  1. Rodney Rehm

    Maybe this Gist helps, too.

  2. Kathirason

    @Rodney, Many thanks for the Gist link..

  3. David Higgins
    Permalink to comment#

    I don’t like the server-side way of doing this. I prefer a client-side solution. Here’s a much better solution. Just drag and drop the file, and it gives you a DATA URI.


  4. Luca

    Nice little snippet. Updated it to automatically get the right image type, without passing it as a parameter.

     * Creates data URI string of an image file for CSS image embedding.
     * @param  [string] $file path to the file
     * @return [string]       data URI string
    function get_data_uri($file) {
        $contents = file_get_contents($file);
        $base64 = base64_encode($contents);
        $imagetype = exif_imagetype($file);
        $mime = image_type_to_mime_type($imagetype);
        return "data:$mime;base64,$base64";
        function data_uri($file) {
            echo get_data_uri($file);
  5. raham sher
    Permalink to comment#

    yaar,please step by step…

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.