Last active
May 24, 2022 13:57
-
-
Save romain-huyvaert/6ac8f8587fc7269b7699ccb7fc6afe00 to your computer and use it in GitHub Desktop.
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 | |
$current_directory = __DIR__; | |
$support_webp = function_exists('imagewebp'); | |
$support_avif = function_exists('imageavif'); | |
if (!$support_webp && !$support_avif) { | |
echo "\n Aucune des deux fonctions imagewebp ou imageavif n'est supportée. \n"; | |
} | |
$all_directories = getAllDirectoriesAndSubDirectories($current_directory, []); | |
foreach ($all_directories as $directory) { | |
if ($support_avif || $support_webp) { | |
$image_filenames = glob($directory.'/*.{gif,jpg,jpeg,png}', GLOB_BRACE); | |
foreach ($image_filenames as $image_filename) { | |
$file_extension = strtolower(pathinfo($image_filename, PATHINFO_EXTENSION)); | |
switch ($file_extension) { | |
case 'gif': | |
$image = imagecreatefromgif($image_filename); | |
imagepalettetotruecolor($image); | |
if ($support_webp) { | |
imagewebp($image, $image_filename.'.webp', 90); | |
} else if ($support_avif) { | |
imageavif($image, $image_filename.'.avif', 40); | |
} | |
break; | |
case 'png': | |
$image = imagecreatefrompng($image_filename); | |
imagepalettetotruecolor($image); | |
if ($support_webp) { | |
imagewebp($image, $image_filename.'.webp', 90); | |
} else if ($support_avif) { | |
imageavif($image, $image_filename.'.avif', 40); | |
} | |
break; | |
case 'jpg': | |
case 'jpeg': | |
$image = imagecreatefromjpeg($image_filename); | |
imagepalettetotruecolor($image); | |
if ($support_webp) { | |
imagewebp($image, $image_filename.'.webp', 90); | |
} else if ($support_avif) { | |
imageavif($image, $image_filename.'.avif', 40); | |
} | |
break; | |
} | |
} | |
} | |
} | |
function getAllDirectoriesAndSubDirectories($directory, $all_directories) { | |
$all_directories[] = $directory; | |
$sub_directories = glob($directory.'/*', GLOB_ONLYDIR); | |
if (!empty($sub_directories)) { | |
foreach ($sub_directories as $sub_directory) { | |
$all_directories = getAllDirectoriesAndSubDirectories($sub_directory, $all_directories); | |
} | |
} | |
return $all_directories; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment