Grow your CSS skills. Land your dream job.

Last updated on:

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. Maybe this Gist helps, too.

  2. @Rodney, Many thanks for the Gist link..

  3. 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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".