Skip to content

Instantly share code, notes, and snippets.

@h-collector
Last active July 4, 2017 17:09
Show Gist options
  • Save h-collector/5757974 to your computer and use it in GitHub Desktop.
Save h-collector/5757974 to your computer and use it in GitHub Desktop.
#!/usr/bin/php -Cq
<?php
$dir = isset($argv[1]) ? $argv[1] : __DIR__;
$skip = isset($argv[2]) ? intval($argv[2]) : 0;
$count = 0;
if(is_dir($dir)){
echo "Dir: {$dir}\n";
echo "Skip: {$skip} files\n";
class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
public function getChildren() {
try {
return new IgnorantRecursiveDirectoryIterator($this->getPathname());
} catch(UnexpectedValueException $e) {
return new RecursiveArrayIterator(array());
}
}
}
$it = new IgnorantRecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS);
$it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
} else {
echo "File: ", $dir, PHP_EOL;
$it = new ArrayIterator(array(new SplFileInfo($dir)));
}
$it = new RegexIterator($it,'/\.png$/i');
$files = array();
$bytestotal = 0;
foreach($it as $file) {
if(++$count > $skip){//$it->seek($skip);
$files[$count] = $file->getPathname();
$bytestotal += $file->getSize();
}
}
echo "Files to optimize: ", ($count-$skip),"/{$count} (".($bytestotal/1024)."KiB)\n";
echo str_repeat('=',42),"\n";
foreach($files as $i => $filepath) {
echo "{$i}/{$count}: {$filepath}\n";
echo str_repeat('+',30),"\n";
$arg = escapeshellarg($filepath);
$fp = popen("optipng -o7 {$arg}", "r"); while(!feof($fp)) echo fgets($fp); fclose($fp);
$fp = popen("pngout {$arg}", "r"); while(!feof($fp)) echo fgets($fp); fclose($fp);
}
sleep(3);//deffered saving?
clearstatcache();
foreach($files as $filepath)
$bytestotal -= filesize($filepath);
echo str_repeat('=',42),"\n";
echo "Space freed on ", count($files), " files (".($bytestotal/1024)."KiB)\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment