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. User Avatar
    Rodney Rehm

    Maybe this Gist helps, too.

  2. User Avatar

    @Rodney, Many thanks for the Gist link..

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

    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. User Avatar
    raham sher
    Permalink to comment#

    yaar,please step by step…

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.