How to set image style in your own module in Drupal 7
Some time ago one of our customers asked to port gallery from Drupal 6 site to Drupal 7 one.
The module was not complex, the main difficult that I faced during the process to change Image Cache approach to the Image style one that native in Drupal 7. The main idea is to set resize rules of thumbnails in the gallery. Users should no do that themselves.
Previously in Drupal 6 there was following solution. The Image Cache preset set in the .install file.
<?php
/**
* Implementation of hook_install().
*/
function ms_gallery_install() {
// Create preset.
ms_gallery_install_imagecache_presets();
function ms_gallery_install_imagecache_presets() {
// First, build an array of all the preset names so we do not make duplicates
// Set the argument to TRUE to reset the cache
$presets = imagecache_presets(TRUE);
$preset_names = array();
// If there are any presets
if ($presets != '') {
foreach ($presets as $preset) {
$preset_names[] = $preset['presetname'];
}
}
// Prepare to install ImageCache presets
$imagecache_presets = array();
$imagecache_actions = array();
// We are checking to make sure the preset name does not exist before creating
if (!in_array('ms_gallery', $preset_names)) {
$imagecache_presets[] = array(
'presetname' => 'ms_gallery',
);
$imagecache_actions['ms_gallery'][] = array(
'action' => 'imagecache_scale_and_crop',
'data' => array(
'width' => 120,
'height' => 67,
),
'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);
foreach ($imagecache_actions[$preset['presetname']] as $action) {
$action['presetid'] = $preset['presetid'];
imagecache_action_save($action);
}
drupal_set_message(t('ImageCache preset %id: %name and corresponding actions saved.', array('%id' => $preset['presetid'], '%name' => $preset['presetname'])));
}
?>
Above the part of ms_gallery.install code. I would like to show how to set Image Cache preset programmatically.
In the case of Drupal
There is no other option than to study Drupal.org. And after several hours I have found following beautiful HOOK hook_image_default_styles()
In terms of this hook to solve my task will be so easy!
<?php
function ms_gallery_image_default_styles() {
$styles = array();
$styles['carousel_gallery'] = array(
'effects' => array(
array(
'name' => 'image_scale_and_crop',
'data' => array(
'width' => 120,
'height' => 67,
'upscale' => 1,
),
'weight' => 0,
),
),
);
return $styles;
?>