Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Using the Drupal 8 Cron API to generate image styles

We saw in a previous post how we could automatically generate the image styles defined on a site for each uploaded source image. We will continue this post for this time to carry out the same operation using the Cron API of Drupal 8, which allows us to desynchronize these mass operations from actions carried out by users, and which can therefore penalize performances.

For the record, the objective is to be able to generate all the image styles of a source image at the time of its import, thus improving the overall performance of the site, especially during the first consultations of its pages.

To achieve our goals, we will create a new Plugin that will extend the QueueWorker plugin. This plugin will allow us to create a specific cron task that we can call and instantiate when importing a source image and thus plan the automatic creation of all image styles.

To create our Plugin, we simply create the file MyModuleImageStyle.php in the src/Plugin/QueueWorker folder of our module.

imageStyleStorage = $image_style_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')->getStorage('image_style')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($data) {
    /** @var \Drupal\file\Entity\File $entity */
    $entity = $data['entity'];
    $styles = $this->imageStyleStorage->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 most significant method of our plugin is the processItem method, which will generate the different image styles when the scheduled task is called via the cron.

So, to take our previous example on generating image styles when importing the source image, we now only need to invoke our new scheduled task (QueueWorker).

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_insert().
 * Generate all image styles once an Image is uploaded.
 */
function my_module_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()) {
      $queue = \Drupal::queue('my_module_image_style');
      $data = ['entity' => $entity];
      $queue->createItem($data);
    }
  }
}

It will then be necessary to configure the cron to be executed on a regular basis, preferably in a decorrelated manner from the user actions, for example by using cron tasks scheduled on the server hosting the website.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web