The world is now ready to webp
https://caniuse.com/webp
The easier (free) way to implement it is to use rewrite, not the picture tag.
<Files *.webp>
Header set Vary "Accept-Encoding"
AddType "image/webp" .webp
AddEncoding webp .webp
</Files>
RewriteCond %{HTTP:Accept} image/webp
RewriteCond %{REQUEST_FILENAME}.webp -f
RewriteRule ^(.*)$ $1.webp [L]
EDIT : Like said in comments, of course you have to generate your webpfile with this filename : filename.jpg.webp for the file filename.jpg
Here a little php function to do this (need GD or imagick):
function generateWebp($paths, $exclude, $compression_quality = 80, $method = 'gd', $replace = false) {
foreach ($paths as $path) {
try {
$Directory = new RecursiveDirectoryIterator($path);
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+(.jpe?g|.JPE?G)$/i', RecursiveRegexIterator::GET_MATCH);
foreach ($Regex as $name => $Regex) {
# Exclusions
if (in_array($name,$exclude)) {
continue;
}
$file = pathinfo($name);
$output_name = $file["dirname"] . '/' . $file["filename"] . '.' . $file["extension"] . '.webp';
# replace webp if new jpg
if (file_exists($output_name) && ($replace || filemtime($name) > filemtime($output_name))) {
unlink($output_name);
}
# if not exist webp, we create it
if (!file_exists($output_name)) {
if ($method === 'gd' && function_exists('imagewebp')) {
switch ($file['extension']) {
case 'jpeg':
case 'jpg':
$image = imagecreatefromjpeg($name);
break;
case 'png':
$image = imagecreatefrompng($name);
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
case 'gif':
$image = imagecreatefromgif($name);
break;
default:
$image = false;
}
if(is_resource($image)){
imagewebp($image, $output_name, $compression_quality);
imagedestroy($image);
echo $output_name . 'généré. ';
}
}
elseif ($method === 'imagemagick' && class_exists('Imagick')) {
$image = new Imagick();
$image->readImage($name);
if ($file_type === 'png') {
$image->setImageFormat('webp');
$image->setImageCompressionQuality($compression_quality);
$image->setOption('webp:lossless', 'true');
}
$image->writeImage($output_name);
}
else {
echo 'GD & IMAGEMAGICK non available';
die('NOK');
}
}
}
} catch (Exception $exception) {
(var_dump($exception));
}
}
}
You can also use a CDN like cloudflare with polish, not free but so conveniant