Skip to content

Instantly share code, notes, and snippets.

@rodrigorm
Created July 15, 2010 13:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigorm/476897 to your computer and use it in GitHub Desktop.
Save rodrigorm/476897 to your computer and use it in GitHub Desktop.
<?php
uses('folder');
uses('file');
class SmushitShell extends Shell {
const service = 'http://smush.it/';
function main() {
$root = $this->params['root'] . DS;
$src = $this->args[0];
if (substr($this->args[1], 0, 7) == 'http://') {
$this->args[2] = $this->args[1];
unset($this->args[1]);
}
if (!empty($this->args[1])) {
$dest = $this->args[1];
} else {
$dest = $src . 'smushit' . DS;
}
$url = $this->args[2];
$srcFolder = new Folder();
if (!$srcFolder->cd($root . $src)) {
$this->error('Invalid path', 'The path ' . $src . ' does not exists');
return false;
}
// $destFolder = new Folder($root . $destFolder, true);
$images = $srcFolder->findRecursive('[^._].*\.(jpg|gif|png)');
$this->out('Smushing ' . count($images) . ' image(s)');
$total = array(
'src_size' => 0,
'dest_size' => 0
);
foreach ($images as $image) {
if (strpos($image, $root . $dest) !== false) {
continue;
}
$img = $url . str_replace(array($root, DS), array('', '/'), $image);
$imgPath = str_replace($root . $src, '', $image);
$stats = $this->_smush($img, $root . $dest . $imgPath, $image);
if (!empty($stats->error)) {
$this->out('Error: ' . $stats->error . "\t" . $imgPath);
} else {
$this->out($stats->src_size . "\t" . $stats->dest_size . "\t" . $stats->percent . "\t" . $imgPath . " -> " . basename($stats->dest));
$total['src_size'] += $stats->src_size;
$total['dest_size'] += $stats->dest_size;
}
}
$percent = (100 * $total['dest_size']) / $total['src_size'];
$savings = 100 - $percent;
$this->out('Total:');
$this->out("\tSrc size: " . $total['src_size']);
$this->out("\tDst size: " . $total['dest_size']);
$this->out("\tSavings: " . round($savings, 2) . ' %');
}
function _smush($img, $dest, $src) {
$url = SmushitShell::service . 'ws.php?img=' . $img;
$handle = curl_init($url);
ob_start();
$return = curl_exec($handle);
$output = ob_get_contents();
ob_end_clean();
$output = json_decode($output);
if (empty($output->error)) {
$handle = curl_init(SmushitShell::service . $output->dest);
ob_start();
curl_exec($handle);
$content = ob_get_contents();
ob_end_clean();
new Folder(dirname($dest), true);
$dest = dirname($dest) . DS . basename($output->dest);
@unlink($dest);
file_put_contents($dest, $content);
}
return $output;
}
}
@tarcisio
Copy link

Nice idea!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment