Thursday, December 06, 2007

This is a not so well known method of embedding images in the HTML file itself. It allows you to include the images and HTML as a single file.

Advantages:

  • one file
  • easier migration
  • less error prone (encoding, binary type during transfer, etc)
  • Less HTTP requests (sometimes faster browser download)

Disadvantages

  • bigger HTML files
  • images not cached for subsequent loading

Here is what the image tag looks like:

<img src="data:image/png;base64,XXX64bit encoded binary dataXXX" />

You can use the following PHP code to generate that tag:
<?php
$fp = fopen('pic.png', 'rb');
$pic = fread($fp, filesize('pic.png'));
fclose($fp);
$base64 = chunk_split(base64_encode($pic));
echo '<img src="data:image/png;base64,'.$base64.'" />';

?>

A nifty trick, that comes very useful in some cases.