Frontendplace Blog

Sharing Frontend developing ideas

img2base64

Posted by info on February 21st, 2011

Lately I stumble more and more on stylesheets that include base64 references to smaller images to prevent an extra html access and have to deal with the server latency. Mainly because I think that developers choose to NOT support IE6 and 7 anymore. You can use this syntax to add a base 64 encoded reference inside your email signature or inside a stylesheet like this: (see http://en.wikipedia.org/wiki/Data_URI_scheme )
As image source


<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />

or inside CSS


ul.checklist li.complete { margin-left: 20px; background:
url('data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/
//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U
g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC')
top left no-repeat; }

With this short piece of php script in your server you can create the base 64 string by passing the reference to the image as an ‘img’ query string. For example http://www.mysite.com/img2base64.php?img=logo.png

<?php
$file = $_GET['img'];
if(!file_exists($file)){
die(“File not found”);
}
else {
if($fp = fopen($file,”rb”, 0)){
$picture = fread($fp,filesize($file));
fclose($fp);
$path_info = pathinfo($file);
$extension =  $path_info['extension'];
// base64 encode the binary data, then break it
// into chunks according to RFC 2045 semantics
$base64 = chunk_split(base64_encode($picture));
echo  ‘<img title=”original image ‘ . $_GET['img'] . ‘” src=”data:image/’.$extension.’;base64,’ . $base64 .
‘”  /> base64 string : ‘ . $base64;
}
}
?>