Drupal 7 : create your own image effect for use in image styles
Par Mathieu le mercredi 25 février 2015, 18:56 - Hacks - Lien permanent
Drupal comes with many predefined effects, you can combine them in image styles to get the picture you want. But what if you have to make your own effect ? Here is how.
Step 1 : create a module
If you are a drupal developer, you should know how to make a module. Okay, I am lazy too :
myeffect.info :
name = My Effect description = "My wonderful border effect" core = 7.x dependencies[] = image files[] = myeffect.module package = Media
Step 2 : declare your effect
Implement hook_image_effect_info :
function myeffect_image_effect_info() { $effects = array( 'myeffect_image_border' => array( 'label' => t('My Effect - Border'), 'help' => t('Add border to an image'), 'effect callback' => '_myeffect_image_border_effect', // Let's make things simpler... // 'form callback' => '_myeffect_image_border_form', // 'summary theme' => '_myeffect_image_border_summary', ), ); return $effects; }
Step 3 : write the callback
function _myeffect_image_border_effect(&$image, $data) { if (!_myeffect_image_border($image, $data)) { watchdog('image', 'Image add border failed using the %toolkit toolkit on %path (%mimetype)', array( '%toolkit' => $image->toolkit, '%path' => $image->source, '%mimetype' => $image->info['mime_type'], ), WATCHDOG_ERROR); return FALSE; } return TRUE; } function _myeffect_image_border(stdClass $image, $data) { if ($image->toolkit == 'gd') { $params = array($image, $data); return call_user_func_array('_myeffect_gd_border', $params); } else { watchdog('image', 'The selected image handling toolkit %toolkit can not correctly process %function.', array( '%toolkit' => $image->toolkit, '%function' => $function, ), WATCHDOG_ERROR); return FALSE; } }
Step 4 : make your effect !
function _myeffect_gd_border(stdClass $image, $data) { $width = $image->info['width']; $height = $image->info['height']; // Note : source image is in $image->resource $dst = imagecreatetruecolor($width, $height); ... // Update image object. $image->resource = $dst; $image->info['width'] = $width; $image->info['height'] = $height; return TRUE; }
Source
The content of this article is widely based on the module Image Effect Kit, you can download and read it for a more complete example.