/** * Implements template_preprocess_responsive_image(). */ function webp_preprocess_responsive_image(&$variables) { $webp_sources = []; if (isset($variables['sources'])) { foreach ($variables['sources'] as $source) { /** @var \Drupal\Core\Template\Attribute $source */ // Blazy module is using another srcset attribute. $srcset_attribute_key = FALSE; if ($source->offsetExists('data-srcset')) { $srcset_attribute_key = 'data-srcset'; } elseif ($source->offsetExists('srcset')) { $srcset_attribute_key = 'srcset'; } if ($srcset_attribute_key !== FALSE) { $srcset_orig = $source->offsetGet($srcset_attribute_key)->value(); /* @var \Drupal\webp\Webp $webp */ $webp = \Drupal::service('webp.webp'); $webp_srcset = $webp->getWebpSrcset($srcset_orig); + // Create the Webp image if it doesn't exist. + $img_paths = explode(', ', $srcset_orig); + $webp_paths = explode(', ', $webp_srcset); + foreach ($webp_paths as $key => $webp_path) { + $img_real_path = explode(' ', $img_paths[$key]); + $img_real_path = \Drupal::service('file_system')->realpath($img_real_path[0]); + $webp_real_path = explode(' ', $webp_path); + $webp_real_path = \Drupal::service('file_system')->realpath($webp_real_path[0]); + if (!file_exists($webp_real_path)) { + exec('/home/ciafcoma/bin/cwebp ' . $img_real_path . ' -o ' . $webp_real_path); + } + } // Create a new source pointing to the webp URL. $webp_source = clone $source; $webp_source->offsetSet($srcset_attribute_key, $webp_srcset); $webp_source->offsetSet('type', 'image/webp'); $webp_sources[] = $webp_source; } } // Add the new sources at the top of the list. - $variables['sources'] = array_merge($webp_sources, $variables['sources']); + // $variables['sources'] = array_merge($webp_sources, $variables['sources']); + + // Replace the sources if WebP is supported. + if (strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== FALSE) { + $variables['sources'] = $webp_sources; + } // Never output a single image tag, because // we will always have at least two sources. $variables['output_image_tag'] = FALSE; } }