View source
<?php
declare (strict_types=1);
use Drupal\file\Entity\File;
use Drupal\Core\Form\FormStateInterface;
function animated_gif_preprocess_image_formatter(&$variables) {
$image = $variables['item'];
$imageValues = $image
->getValue();
$file = File::load($imageValues['target_id']);
if ($file && $file
->getMimeType() === 'image/gif' && _animated_gif_is_animated($file
->getFileUri())) {
$variables['image']['#theme'] = 'image';
unset($variables['image']['#style_name']);
unset($variables['image_style']);
}
}
function animated_gif_preprocess_responsive_image_formatter(&$variables) {
$image = $variables['item'];
$imageValues = $image
->getValue();
$file = File::load($imageValues['target_id']);
if ($file && $file
->getMimeType() === 'image/gif' && _animated_gif_is_animated($file
->getFileUri())) {
$variables['responsive_image']['#theme'] = 'image';
unset($variables['image']['#responsive_image_style_id']);
unset($variables['image_style']);
}
}
function animated_gif_preprocess_image_style(&$variables) {
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadByProperties([
'uri' => $variables['uri'],
]);
if (empty($files)) {
return;
}
$file = reset($files);
if ($file
->getMimeType() === 'image/gif' && _animated_gif_is_animated($file
->getFileUri())) {
$variables['image']['#uri'] = $variables['uri'];
unset($variables['image']['#style_name']);
unset($variables['image_style']);
unset($variables['style_name']);
}
}
function animated_gif_field_widget_image_image_form_alter(&$element, FormStateInterface $form_state, $context) {
if (!empty($element['#default_value']['fids'])) {
$fid = reset($element['#default_value']['fids']);
$file = File::load($fid);
if ($file && $file
->getMimeType() === 'image/gif' && _animated_gif_is_animated($file
->getFileUri())) {
$element[] = [
'#type' => 'container',
'#markup' => t('GIF images are not being processed by image styles, use with caution!'),
'#attributes' => [
'class' => [
'messages',
'messages--warning',
],
],
];
}
}
}
function _animated_gif_is_animated(string $fileUri) : bool {
$fopen = @fopen($fileUri, 'rb');
if (!$fopen) {
return FALSE;
}
$count = 0;
while (!feof($fopen) && $count < 2) {
$chunk = fread($fopen, 1024 * 100);
$count += preg_match_all('#\\x00\\x21\\xF9\\x04.{4}\\x00[\\x2C\\x21]#s', (string) $chunk);
}
fclose($fopen);
return $count > 1;
}