neil_pearce

Convert images to WebP

Jun 25th, 2022 (edited)
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.99 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. function convert_images(string $directory): void {
  6.     $directory = realpath($directory);
  7.  
  8.     if ($dh = opendir($directory)) {
  9.         /* process all the files in the specified directory */
  10.         while (($file = readdir($dh)) !== false) {
  11.             if (
  12.                 in_array($file, ['.', '..'])
  13.                 || is_dir("$directory/$file")
  14.                 || is_link("$directory/$file")
  15.             ) {
  16.                 /* exclude directories and symbolic links */
  17.                 continue;
  18.             }
  19.  
  20.             if (
  21.                 ($image_type = exif_imagetype("$directory/$file")) === false
  22.                 || ! in_array($image_type, [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG])
  23.                 || ($image_extension = image_type_to_extension($image_type, false)) === false
  24.             ) {
  25.                 /* only process certain image types */
  26.                 continue;
  27.             }
  28.  
  29.             /* create an image based on the image file format */
  30.             $image_create = 'imagecreatefrom' . $image_extension;
  31.             if (($image = $image_create("$directory/$file")) === false) {
  32.                 echo 'failed to create image from ', $file, PHP_EOL;
  33.                 continue;
  34.             }
  35.  
  36.             /* format the WebP filename */
  37.             $webp = "$directory/" . pathinfo($file, PATHINFO_FILENAME)
  38.                     . image_type_to_extension(IMAGETYPE_WEBP);
  39.  
  40.             /* delete the WebP file if it already exists */
  41.             if (file_exists($webp)) {
  42.                 if (unlink($webp) === false) {
  43.                     echo 'failed to delete ', $webp, PHP_EOL;
  44.                     continue;
  45.                 }
  46.             }
  47.  
  48.             /* generate the WebP image */
  49.             $quality = 10;  // see documentation for imagewebp
  50.             if (imagewebp($image, $webp, $quality) === false) {
  51.                 echo 'failed to convert ', $file, PHP_EOL;
  52.             }
  53.         }
  54.  
  55.         closedir($dh);
  56.     }
  57. }
Add Comment
Please, Sign In to add comment