Need some help with your project? Contact me

I’m Hooked! 5: Declaring your own image styles with a Drupal hook

This week we look at how you can programatically declare your own image styles using hook_image_default_styles(). Say your module uses images that need to conform to a certain size and position in their context. You can use this hook to create a style that you can then apply to the image in the theme layer.

OK, so let’s get down to it. This is the code and the explanation comes after:

function demo_image_default_styles() {
  $styles = array();

  $styles['demo_thumb'] = array(
    'effects' => array(
        'name' => 'image_scale',
        'data' => array(
          'width' => 200,
          'upscale' => 1,
        'weight' => 0,
        'name' => 'image_crop',
        'data' => array(
          'width' => 200,
          'height' => 200,
        'weight' => 1,

  return $styles;

A little bit of context first. Let’s say our module creates some sort of a blogging feature that requires the automatic creation and display of some thumbnail images. The code above only handles the part of defining the image style with its effects and is quite easy to understand.

A new image style called demo_thumbnail is created. This style applies an image_scale and crop effect to the image in view of getting a resulting image of 200x200 px. I'm sure you are already familiar with what these effects are from the core Image module. So it’s not difficult. All you have to do is include the effects you want and configure them according to their specific parameters.

If you clear your caches and go to admin/config/media/image-styles you’ll see the new default image style called demo_thumb just like the other three ones defined by the Image module: thumbnail, medium and large.

Next week when we look at another hook, I will also show you how to programatically replace the image style used when rendering a particular image. See you then.


Nice one............... really handy.
Thanks for sharing.

How about anchor on image_crop? Can't find any answers on that subject.

Add new comment

You must have Javascript enabled to use this form.