Skip to content

Instantly share code, notes, and snippets.

@crosma
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crosma/8969330 to your computer and use it in GitHub Desktop.
Save crosma/8969330 to your computer and use it in GitHub Desktop.
$destination_file
//Run gifsicle regardless
$old_size = filesize($destination_file);
//Now to try all the different compressions (you never know which will be best)
$options = array('-O1', '-O2', '-O3', '-O1 --colors 256', '-O2 --colors 256', '-O3 --colors 256');
$count = count($options);
for ($i=0; $i<$count; $i++)
{
system('gifsicle '.$options[$i].' "'.$destination_file.'" > "'.$dest.'.test'.$i.'"');
$options[$i] = filesize($destination_file.'.test'.$i);
}
asort($options); //sort to find the smallest file
$keys = array_keys($options);
rename($destination_file.'.test'.($keys[0]), $dest);
for ($i=0; $i<$count; $i++)
{
unlink($destination_file.'.test'.$i);
}
clearstatcache(); //needed to clear file stats cached by php
log('Saved '.number_format($old_size - filesize($destination_file)).' bytes. ('.round(($old_size - filesize($destination_file))/$old_size*100).'%)');
$cmd = sprintf('convert "%s" -coalesce', $source_file);
if ($crop)
{
$cmd .= sprintf(' -crop %dx%d+%d+%d\!', $w, $h, $x, $y);
}
if ($resize)
{
$cmd .= sprintf(' -filter Lanczos -resize %dx%d\!', $new_width, $new_height);
}
$cmd .= sprintf(' +dither -colors 256 -treedepth 3 +repage "%s"', $destination_file);
system($cmd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment