Prevent Drupal from applying image styles to GIFs, SVGs

Profile picture for user a.berramou
Azz-eddine BERRAMOU 15 June, 2023

I am currently working on a website where the editorial team occasionally creates animated GIFs, and SVG and incorporates them into articles. However, there is an issue with how Drupal handles image styles and animated GIFs by default.

The standard image processing library used by Drupal, GD, does not preserve the animation of GIFs when it processes them, and crop SVG images. Consequently, applying any image styles to a GIF will result in the removal of its animation, and crop and ruin SVG images.

After conducting thorough investigation, I have created an implementation of the hook_entity_display_build_alter. This particular hook enables you to alter the render array generated by an EntityDisplay for an entity across all view modes.

In my implementation, I make use of this hook to eliminate the image style applied to the currently rendered image.

 * Implements hook_entity_display_build_alter().
function [MODULE_NAME]_entity_display_build_alter(&$build, $context) {
  $entity = $context['entity'];
  $media_bundles = ['image', 'logo'];
  $image_extensions = ['image/gif', 'image/svg+xml'];
  if (
    $entity->getEntityTypeId() == 'media' &&
    in_array($entity->bundle(), $media_bundles) &&
    $context['view_mode'] == 'full'
  ) {
    if (isset($build['field_media_image'])) {
      $mimetype = $build['field_media_image'][0]['#item']->entity->filemime->value ?? '';
      $image_style = $build['field_media_image'][0]['#image_style'] ?? NULL;
      if (in_array($mimetype, $image_extensions) && !empty($image_style)) {
        $build['field_media_image'][0]['#image_style'] = '';

As a result, the image style that has been configured for this specific display mode (full mode in my case) will now be applied to JPEGs and PNGs as intended. However, it will no longer be applied to GIFs and SVGs.

And it's done now just clear your cache!

I hope this article helps.