Installing ImageCache Presets From Your Drupal Module

Photo of Greg Harvey
Thu, 2009-01-22 13:46By greg

For those of you unfamiliar with the ImageCache module, get familiar here:
http://drupal.org/project/imagecache

It's pretty useful, allowing you to define preset image sizes that will be automatically generated whenever an image is uploaded to your site (providing the module doing the upload supports ImageCache which, fortunately, most do - including the Image module and the frighteningly useful ImageField CCK module).

If you're a module developer trying to pre-install some ImageCache presets, there is currently no import/export behaviour (see CCK, Views, Panels and the like for an example of what I mean) but that's ok. Firstly, they're working on it:
http://drupal.org/node/255421

Secondly, ImageCache already handles everything you need to do to save a preset and some actions in two easy-to-use and sensibly named functions - imagecache_preset_save() and (can you guess what it is yet?) imagecache_action_save(). And, rather usefully, the module developer had the good sense to return the $preset array from the imagecache_preset_save() function for a newly created preset so you can pass the ID in your subsequent action saves. Nice! =)

To save you the trouble of working this out, here is the code I knocked up for the hook_install() of the simple CCK Gallery module I'm putting together. It creates a couple of presets and then saves their corresponding actions using the exposed ImageCache functions:

/**
* Implementation of hook_install()
*/
function cck_gallery_install() {

//install ImageCache presets
$imagecache_presets = array(
array(
'presetname' => 'thumbnail',
),
array(
'presetname' => 'normal',
),
);

$imagecache_actions = array(
'thumbnail' => array(
'action' => 'imagecache_scale',
'data' => array(
'width' => 120,
'height' => 120,
'upscale' => 1,
),
'weight' => 0,
),
'normal' => array(
'action' => 'imagecache_scale',
'data' => array(
'width' => 800,
'height' => 600,
'upscale' => 0,
),
'weight' => 0,
),
);

//need to install preset, id will be returned by function,
//then install action add presetid to action prior to install:
foreach ($imagecache_presets as $preset) {
$preset = imagecache_preset_save($preset);
$imagecache_actions[$preset['presetname']]['presetid'] = $preset['presetid'];
imagecache_action_save($imagecache_actions[$preset['presetname']]);
drupal_set_message(t('ImageCache preset %id: %name and corresponding actions saved.', array('%id' => $preset['presetid'], '%name' => $preset['presetname'])));
}
}
?>

Don't forget you need to either wrap that stuff in an if (module_exists('imagecache')) or make ImageCache a dependency in your module's info file.