How to import images directly into the html code (base64)

A couple of months ago I received an interesting task - to create a small html application for iPhone. To be honest, for me that meant creating a small site with a specific size. Of course I was wrong. Together with couple of small bugs I had to deal with one other requirement - everything had to be in one html file. It was clear how to add the javascript and the css, but what about the images.

The solution was to use base64 encoding. I wrote a small php script that accepts an image and shows me the equivalent in base64 string.

    $base64 = "";
    $css = "";
    $tag = "";
        $file = rand(0, 10000000).$_FILES['f']['name'];
        if (move_uploaded_file($_FILES['f']['tmp_name'], $file)) {
            if($fp = fopen($file,"rb", 0))
               $picture = fread($fp,filesize($file));
               // base64 encode the binary data, then break it
               // into chunks according to RFC 2045 semantics
               $base64 = base64_encode($picture);
               $tag = '<img src="data:image/jpg;base64,'.$base64.'" alt="" />';
               $css = 'url(data:image/jpg;base64,'.str_replace("\n", "", $base64).'); ';
<head><title>Base64 img convert</title></head>
    <form action="./index.php" method="post" enctype="multipart/form-data">
        <input type="file" name="f">
        <input type="submit">
    The CSS code:
    <textarea style="width:800px;height:100px;font-size:10px;"><?php echo $css; ?></textarea>
    The HTML code:
    <textarea style="width:800px;height:100px;font-size:10px;"><?php echo $tag; ?></textarea>
    <?php echo $tag; ?>

Just browse your image and click "Submit Query".

base64 doesn't work in IE
blog comments powered by Disqus