Created
May 9, 2012 19:44
-
-
Save martinsbalodis/2648299 to your computer and use it in GitHub Desktop.
Simple php CLI script for replacing css background images with base64 encoded images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Simple php CLI script for replacing css background images with base64 encoded | |
* images. | |
* | |
* Usage: | |
* base64imagescss.php ../../your/path/in.css out.css | |
* | |
* @author Martins Balodis | |
* @link https://github.com/martinsbalodis | |
*/ | |
if (count($argv) !== 3) { | |
throw new Exception("Invalid arg count"); | |
} | |
$css_in = file_get_contents($argv[1]); | |
$base_dir = dirname($argv[1]).'/'; | |
$allowed_mimes = array('image/jpeg', 'image/png', 'image/gif', 'image/jpg'); | |
$css_out = preg_replace_callback('#url\(([a-z0-9/_\.]+)\)#', function($matches) use($base_dir, $allowed_mimes) { | |
$image_location = $base_dir . $matches[1]; | |
// check image exists | |
if (!is_file($image_location)) { | |
throw new Exception("Image not found - " . $image_location); | |
} | |
$imageinfo = getimagesize($image_location); | |
if (!isset($imageinfo['mime'])) { | |
throw new Exception("error when trying to load image info - " . $image_location); | |
} | |
// check image mime | |
if (!in_array($imageinfo['mime'], $allowed_mimes)) { | |
throw new exception("Invalid image mime - " . $imageinfo['mime'] . ', ' . $image_location); | |
} | |
return 'url(data:' . $imageinfo['mime'] . ';base64,' . base64_encode(file_get_contents($image_location)) . ')'; | |
}, $css_in); | |
file_put_contents($argv[2], $css_out); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment