Skip to content

Instantly share code, notes, and snippets.

@Gargaj
Last active August 29, 2015 14:14
Show Gist options
  • Save Gargaj/f078c8e66c85bcb180fc to your computer and use it in GitHub Desktop.
Save Gargaj/f078c8e66c85bcb180fc to your computer and use it in GitHub Desktop.
Script to convert small images into inline base64 in CSS
<?
$inputFile = "";
$outputFile = "";
$sizeLimit = 10 * 1024;
for ($x = 1; $x<count($argv); $x++) {
switch ($argv[$x]) {
case "--output":
case "-o":
{
$outputFile = $argv[++$x];
} break;
case "--limit":
case "-l":
{
$sizeLimit = (int)$argv[++$x];
} break;
default:
{
$inputFile = $argv[$x];
} break;
}
}
if (!file_exists($inputFile))
{
die(print_r($argv));
}
if (!$outputFile)
$outputFile = str_replace(".css",".b64.css",$inputFile);
$data = file_get_contents($argv[1]);
$data = preg_replace_callback("/url\((.*?)\)/",function($m){
global $sizeLimit;
$file = trim($m[1],"\"'");
echo $file." ... ";
if (!file_exists($file))
{
echo "file not found\n";
return $m[0];
}
if (filesize($file) > $sizeLimit)
{
echo "file is ".(int)(filesize($file)/1024)."k, skipping\n";
return $m[0];
}
list($width, $height, $type, $attr) = getimagesize($file);
$sep = "\\\n ";
$data = "url('data:".image_type_to_mime_type($type).";base64,".$sep;
$fileRaw = file_get_contents($file);
$data .= trim(chunk_split(base64_encode($fileRaw),76,$sep),"\n \\");
$data .= "')";
echo "done\n";
return $data;
},$data);
file_put_contents($outputFile,$data);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment