Created
November 12, 2018 19:53
-
-
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
This file contains 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 | |
// 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