How To Convert PNG To WebP Image Format In PHP With Example?

function yttags_png2webp($src_file_path, $file_destination_path, $compression_qty = 100)
{
    $image = imagecreatefrompng($src_file_path);
    imagepalettetotruecolor($image);
    imagealphablending($image, true);
    imagesavealpha($image, true);
    $final_output = imagewebp($image, $file_destination_path, $compression_qty);
    if (false === $final_output) {
        return false;
    }
    imagedestroy($image);
    return $file_destination_path;
}

Function usage:

echo yttags_png2webp('img/oldfile.png','img/newfile.webp',100);

Example Converting PNG images to WebP using PHP

Installing PHP-GD

$ sudo apt-get install php8.1-gd

convert PNG images to WebP format

$imagesDirectory = 'uploads/';
$imageName = 'mylove.png';
$webpImageName = 'newgf.webp';

$gdImageInstance = imagecreatefrompng($imagesDirectory . $imageName);
$conversionSuccess = imagewebp(
    $gdImageInstance, 
    $imagesDirectory . $webpImageName, 
    100
);

if ($conversionSuccess) {
    imagedestroy($gdImageInstance);

    echo 'Good Luck, Conversion successful!';
}

Leave a Comment