Generate programmatically image styles with Drupal 8

Horses running

Drupal 8 allows you to generate image styles for various effects (reduction, cut-out, black-and-white, saturation, etc.) for each uploaded image. You can very quickly have many images styles, and even more if you use responsive images, allowing to propose different dimensions according to the terminal used to consult your website.

These image styles are generated during a first lookup of a page using these, which can be penalizing in terms of performance or even rendering, when you have many media, with so many image styles as break points, such as on a landing page or a listing page.

The snippet below will allow you to automatically generate all possible image styles when uploading the source image.

use Drupal\image\Entity\ImageStyle;
use Drupal\Core\Entity\EntityInterface;
use Drupal\file\FileInterface;

/**
 * Implements hook_entity_insert().
 * Generate all image styles once an Image is uploaded.
 */
function MYMODULE_entity_insert(EntityInterface $entity) {
  /** @var \Drupal\file\Entity\File $entity */
  if ($entity instanceof FileInterface) {
    $image = \Drupal::service('image.factory')->get($entity->getFileUri());
    /** @var \Drupal\Core\Image\Image $image */
    if ($image->isValid()) {
      $styles = ImageStyle::loadMultiple();
      $image_uri = $entity->getFileUri();
      /** @var \Drupal\image\Entity\ImageStyle $style */
      foreach ($styles as $style) {
        $destination = $style->buildUri($image_uri);
        $style->createDerivative($image_uri, $destination);
      }
    }
  }
}

The result will be a slightly longer time for the editor, when he will save the content, but a consequent gain for the visitors, in terms of performance and speed of loading pages, because then all the possible versions of a source image will have already been generated, avoiding many PHP calls during the first lookup of a page, especially if it contains many images.

To improve the user experience, it is also possible to use the Cron API of Drupal 8 to queue the generation of these image styles when saving a source image, reducing the saving time for editors. But this may be the subject of another post.

 

Ajouter un commentaire