Restored guide

Programmatically generate all images for each ImageCache preset using a Drush PHP script

November 26, 2010 · 2 min read · Eric London's Drupal Blog

ImageCache builds a derivative the first time a browser asks for it. After you add a preset, or after a cold cache, that work lands on a page view and can die with "Premature end of script headers" when PHP hits memory_limit. Generate the files from Drush instead.

What you are solving

Each preset is a recipe (scale, crop, or both) stored by the ImageCache module. The derivative path looks like imagecache/PRESET/relative/path.jpg. Calling that URL from the site warms one file. A script can walk the source files and warm every preset you care about while a CLI process, with a higher memory limit, does the work.

List presets and sources

On Drupal 6 the preset list is available once ImageCache is loaded. Source files usually live under the public files directory. Skip SVG and other formats the toolkit will not read.

// scripts/warm-imagecache.php
// drush scr ../scripts/warm-imagecache.php
$presets = imagecache_presets();
$base = file_directory_path();
$allowed = array('jpg', 'jpeg', 'png', 'gif');
$files = file_scan_directory($base, '.*', array('.', '..', 'imagecache'), 0, TRUE);

Build one derivative at a time

Prefer the ImageCache API that writes a derivative from a source path over fetching your own HTTP stack in a loop. If you do request the public URL, do it one file at a time, log the status, and stop on a memory error instead of continuing blind.

foreach ($presets as $preset) {
  foreach ($files as $file) {
    $ext = strtolower(pathinfo($file->filename, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed, TRUE)) {
      continue;
    }
    imagecache_build_derivative($preset['actions'], $file->filename, imagecache_create_path($preset['presetname'], $file->filename));
  }
}

Function names differ slightly across ImageCache releases. Open imagecache.module on the site you are running and call the derivative builder that release actually defines. The pattern is the same: preset actions, source, destination.

Check before you deploy

  • Run against one directory and confirm the files appear under imagecache/PRESET.
  • Raise the CLI memory limit in the Drush environment, not necessarily in the web php.ini.
  • Do not delete source files. Derivatives are disposable; originals are not.

Restored guide for the 26 November 2010 note on warming ImageCache presets with Drush.