Convert png, jpg, jpeg, gif to webp using PHP Function

To convert PNG, JPG, JPEG, and GIF files to WebP format using PHP, you can use the GD library and imagewebp() function. Here's an example code snippet that should do the trick:

function convertToWebP($sourcePath, $destinationPath) {
    // Check if the file is a supported image type
    $mime = mime_content_type($sourcePath);
    if ($mime == 'image/png') {
        $image = imagecreatefrompng($sourcePath);
    } elseif ($mime == 'image/jpg' || $mime == 'image/jpeg') {
        $image = imagecreatefromjpeg($sourcePath);
    } elseif ($mime == 'image/gif') {
        $image = imagecreatefromgif($sourcePath);
    } else {
        return false;
    // Convert the image to WebP and save it
    imagewebp($image, $destinationPath, 80);
    // Free up memory
    return true;

// Example usage
convertToWebP('image.png', 'image.webp');
convertToWebP('photo.jpg', 'photo.webp');
convertToWebP('animation.gif', 'animation.webp');

Note that not all browsers support the WebP format, so you may want to consider providing fallback formats like PNG or JPEG in case the user's browser doesn't support WebP.