Nice PHP function to convert images to WebP

Post Photo
Saturday, 26th September 2020

WebP is becoming the new web standard regarding photos on the web today. PHP 7+ makes things really easy for you

It's as simple as that. Just copy-paste the following code in your project and you are ready to go.

Have fun!

/**
* Convert Image to WebP
*/

function conv_img2webp($source, $destination, $quality=75) {
    $extension = strtolower(pathinfo($source, PATHINFO_EXTENSION));
    switch($extension){
        case 'bmp' : $img = imagecreatefromwbmp($source); break;
        case 'gif' : $img = imagecreatefromgif($source); break;
        case 'jpg' : $img = imagecreatefromjpeg($source); break;
        case 'jpeg': $img = imagecreatefromjpeg($source); break;
        case 'png' : $img = imagecreatefrompng($source); break;
        default : return "Unsupported picture type!";
    }

    imagepalettetotruecolor($img);
    imagealphablending($img, true);
    imagesavealpha($img, true);
    imagewebp($img, $destination, $quality);
    imagedestroy($img);
}

Share Post

If you like this post please share with your friends