Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- function convert_images(string $directory): void {
- $directory = realpath($directory);
- if ($dh = opendir($directory)) {
- /* process all the files in the specified directory */
- while (($file = readdir($dh)) !== false) {
- if (
- in_array($file, ['.', '..'])
- || is_dir("$directory/$file")
- || is_link("$directory/$file")
- ) {
- /* exclude directories and symbolic links */
- continue;
- }
- if (
- ($image_type = exif_imagetype("$directory/$file")) === false
- || ! in_array($image_type, [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG])
- || ($image_extension = image_type_to_extension($image_type, false)) === false
- ) {
- /* only process certain image types */
- continue;
- }
- /* create an image based on the image file format */
- $image_create = 'imagecreatefrom' . $image_extension;
- if (($image = $image_create("$directory/$file")) === false) {
- echo 'failed to create image from ', $file, PHP_EOL;
- continue;
- }
- /* format the WebP filename */
- $webp = "$directory/" . pathinfo($file, PATHINFO_FILENAME)
- . image_type_to_extension(IMAGETYPE_WEBP);
- /* delete the WebP file if it already exists */
- if (file_exists($webp)) {
- if (unlink($webp) === false) {
- echo 'failed to delete ', $webp, PHP_EOL;
- continue;
- }
- }
- /* generate the WebP image */
- $quality = 10; // see documentation for imagewebp
- if (imagewebp($image, $webp, $quality) === false) {
- echo 'failed to convert ', $file, PHP_EOL;
- }
- }
- closedir($dh);
- }
- }
Add Comment
Please, Sign In to add comment