Skip to content

Instantly share code, notes, and snippets.

@arminrosu
Last active June 6, 2016 22:05
Show Gist options
  • Save arminrosu/4039144 to your computer and use it in GitHub Desktop.
Save arminrosu/4039144 to your computer and use it in GitHub Desktop.
Batch base64 encode images in a directory for CSS
<pre><?php
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* Batch base64 encode images and output css
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
// list images in ./images/ directory
$directory = dirname(realpath(__FILE__));
$images_dir = $directory . '/images/';
$images = get_images($images_dir);
// parse them
foreach ($images as $filename) {
//
$css = "//$filename\n";
// extension
$mime = get_mime_type( $images_dir . $filename, PATHINFO_EXTENSION);
// encode
$string = file_get_contents($images_dir . $filename);
$encoded = base64_encode($string);
// css
$css .= "background-image:url('data:$mime;base64,$encoded')\n\n";
echo $css;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* Helpers
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
// get files in directory
function get_images($dir) {
return glob( $dir . '*');
}
function get_mime_type( $file ) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
// we cool?!
if (!$finfo) :
// fallback
$mime_types = array(
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png'
);
$extension = pathinfo($file, PATHINFO_EXTENSION);
$type = $mime_types[$extension];
else :
$type = $finfo->file($file);
endif;
return $type;
}
?></pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment