Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

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.

<?php
  $base64 = "";
  $css = "";
  $tag = "";
  
  if(isset($_FILES['f']['name'])) {
    $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));
        fclose($fp);
        // 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).'); ';
      }
    }
  }
?>
<html>
   <head>
      <title>Base64 img convert</title>
   </head>
   <body>
      <form action="./index.php" method="post" enctype="multipart/form-data">
        <input type="file" name="f">
        <input type="submit">
      </form>
      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; ?>
   </body>
</html>

Just browse your image and click "Submit Query".

P.S. base64 doesn't work in IE

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.