Converting .png and .jpg Images to .webp Can Improve Your Site Performance with This Free PHP Script

<?php

// Check if the GD extension is enabled. This is required for image functions.
if (!extension_loaded('gd')) {
    echo "The GD extension is not enabled. Please enable it in your php.ini file.";
    exit;
}

// Set a high execution time limit for large folders
set_time_limit(300); 

// Define the quality for the WEBP conversion. 100 means no quality loss.
$quality = 100;

// The folder containing your images. In this case, it's the current directory.
$directory = '.';

// Scan the current directory for image files.
$files = scandir($directory);

// Loop through each file found in the directory.
foreach ($files as $file) {
    // Skip the current and parent directory links.
    if ($file === '.' || $file === '..') {
        continue;
    }

    // Get the file extension.
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    // Check if the file is a JPG or a PNG.
    if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'png') {
        
        // Define the output file name with the .webp extension.
        $output_file = pathinfo($file, PATHINFO_FILENAME) . '.webp';

        // Skip conversion if a WEBP file with the same name already exists.
        if (file_exists($output_file)) {
            echo "Skipping {$file}, {$output_file} already exists.<br>";
            continue;
        }

        // --- Load the image based on its type ---
        $image = false;
        if ($extension === 'jpg' || $extension === 'jpeg') {
            $image = imagecreatefromjpeg($file);
        } elseif ($extension === 'png') {
            // Preserve transparency for PNGs.
            $image = imagecreatefrompng($file);
            imagepalettetotruecolor($image);
            imagealphablending($image, true);
            imagesavealpha($image, true);
        }

        // If the image was loaded successfully, save it as a WEBP.
        if ($image !== false) {
            imagewebp($image, $output_file, $quality);
            imagedestroy($image); // Free up memory.
            echo "Successfully converted {$file} to {$output_file}<br>";
        }
    }
}

echo "Conversion complete!";
?>
Leave a Reply 0

Your email address will not be published. Required fields are marked *