Images inside a CSS file
Posted by Tom on May 28th, 2010I was experimenting with my own version of the CSS3 Awesome button, when I noticed one of the commenters share the base64 encoded version of the semi-transparent PNG image they were using as a substitute for a gradient.
I was using a smaller image, and want to run a conversion of my own (it saves an extra HTTP connection, making it easier on both the client’s browser and the server). A quick trip to Google turned up an online conversion tool that worked great.
Wikipedia also provides sample code for doing conversions with PHP: (Please notice there is no error handling!)
<?php
header('Content-type: text/css');
function data_uri($file, $mime) {
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
body {
background-image:url('<?php echo data_uri('elephant.png', 'image/png'); ?>');
}
