Convert images to WebP using PHP

PHP code snippet to convert jpeg, png and gif images to the modern image format WebP.

The following PHP code snippet accepts an image path, then depending on what PHP extensions you have installed it either uses PHP GD or Imagick to convert png, jpeg, or gif images to WebP. On success the WebP image will be written to file and the new file path returned.


 * Generate Webp image format
 * Uses either Imagick or imagewebp to generate webp image
 * @param string $file Path to image being converted.
 * @param int $compression_quality Quality ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file).
 * @return false|string Returns path to generated webp image, otherwise returns false.
function jcphp01_generate_webp_image($file, $compression_quality = 80)
    // check if file exists
    if (!file_exists($file)) {
        return false;

    // If output file already exists return path
    $output_file = $file . '.webp';
    if (file_exists($output_file)) {
        return $output_file;

    $file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    if (function_exists('imagewebp')) {

        switch ($file_type) {
            case 'jpeg':
            case 'jpg':
                $image = imagecreatefromjpeg($file);

            case 'png':
                $image = imagecreatefrompng($file);
                imagealphablending($image, true);
                imagesavealpha($image, true);

            case 'gif':
                $image = imagecreatefromgif($file);
                return false;

        // Save the image
        $result = imagewebp($image, $output_file, $compression_quality);
        if (false === $result) {
            return false;

        // Free up memory

        return $output_file;
    } elseif (class_exists('Imagick')) {
        $image = new Imagick();

        if ($file_type === 'png') {
            $image->setOption('webp:lossless', 'true');

        return $output_file;

    return false;

Leave a Reply

Fields marked with an * are required to post a comment