Triggering the creation of imagecache derivatives programmatically

Feb 22, 2009

I was recently faced with the same problem in two different projects: forcing the creation of an image derivative with imagecache so that it is available in the submit handler of the same form in which the image was uploaded. By default, imagecache generates images on demand triggered by an HTTP request, which is ideal for most cases. However, this design doesn't make it possible to trigger the generation of images programmatically, which is why I created the following code snippet.

<?php
function imagecache_generate($presetname, $filepath) {
  if (!$preset = imagecache_preset_by_name($presetname)) {
    return;
  }
  
  $dst = imagecache_create_path($presetname, $filepath);
  
  if (!file_exists($dst)) {
imagecache_build_derivative($preset['actions'], $filepath, $dst);
  }
  
  return $dst;
}
?>

This snippet is based on _imagecache_cache(), but instead of transferring an image in response to an HTTP request, it returns the path to the generated image.

Note that you do not need to do this unless you are doing some special processing with your image (in my case: including it in a generated PDF document or passing it as a parameter to a command-line executable which generates "magic eye" images).