Profile picture for user admin
Daniel Sipos
06 Mar 2013

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(
      array(
        'name' => 'image_scale',
        'data' => array(
          'width' => 200,
          'upscale' => 1,
        ),
        'weight' => 0,
      ),
      array(
        '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.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Comments

tusharbodke 06 Mar 2013 13:32

Nice one...............

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

Henk 20 Aug 2014 17:18

How about anchor on image

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

Add new comment