Skip to content

Instantly share code, notes, and snippets.

@lyquix-owner
Created November 12, 2018 19:53
Show Gist options
  • Save lyquix-owner/06f686ff82b2dbc65ffaefdc6c4362a3 to your computer and use it in GitHub Desktop.
Save lyquix-owner/06f686ff82b2dbc65ffaefdc6c4362a3 to your computer and use it in GitHub Desktop.
Recursively scans directory for jpg files and saves optimized versions using the same directory structure
<?php
// JPEG quality level
$quality = 85;
// Recursively scan directory and get jpeg images
$sourceDir = __DIR__ . '/original';
$targetDir = __DIR__ . '/optimized';
function getFiles($dir) {
if(is_dir($dir)) {
$arr = [];
$files = glob($dir . '/*.jp*');
foreach($files as $file) {
$arr[] = $file;
}
$subdirs = glob($dir . '/*', GLOB_ONLYDIR);
foreach($subdirs as $subdir) {
$arr = array_merge($arr, getFiles($subdir));
}
return $arr;
}
else die($dir . ' is not a directory');
}
function optimizeImage($src, $dest, $quality) {
$info = getimagesize($src);
if($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($src);
$destDir = substr($dest, 0, strrpos($dest, '/'));
if(!is_dir($destDir)) mkdir($destDir, 0755, true);
imagejpeg($image, $dest, $quality);
}
}
$files = getFiles($sourceDir);
foreach($files as $key => $file) {
unset($files[$key]);
$newFile = str_replace($sourceDir, $targetDir, $file);
optimizeImage($file, $newFile, $quality);
$fileSize = filesize($file);
$newFileSize = filesize($newFile);
$files[$file] = [
'original' => $fileSize,
'optimized' => $newFileSize,
'absolute' => $fileSize - $newFileSize,
'percent' => (100 * ($fileSize - $newFileSize) / $fileSize) . '%'
];
}
echo json_encode($files);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment