Programmatically Create & Delete Image Styles in Drupal

Need to programmatically create or delete an image style in Drupal? Maybe you’re creating a module that needs to define a new style or looking to use an update handler to delete one. It’s a cinch to do with just a few lines of code.

Drupal

I recently needed to delete a image style that was no longer being used with a update handler. Being that Drupal’s documentation is less than informative, I did some digging and finally figured it out. Check out how to create, flush and delete image styles below.

Programmatically Create an Image Style

The code below will create an image style named, avatar that will scale images to 64×64:

<?php
$style = image_style_save(array('name' => 'avatar'));
$effect = array(
  'name' => 'image_scale',
  'data' => array(
    'width' => 64,
    'height' => 64,
    'upscale' => TRUE,
  ),
  'isid' => $style['isid'],
);
image_effect_save($effect);

Or, you can create image styles with a Drupal hook using hook_image_default_styles:

<?php
function hook_image_default_styles() {
  $styles = array();
  $styles['avatar'] = 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;
}

Programmatically Delete an Image Style

<?php
image_style_delete(image_style_load('my_image_style'));

Don’t forget to flush…

You may need to flush the image style before Drupal will let you delete it. You can flush image styles using two different methods:

Flush Image Styles with Drupal Console

# List image styles on the site
$ drupal image:styles:debug

# Execute flush function by image style or execute all flush images styles
$ drupal image:styles:flush

For a list of other useful Drupal 8 Console commands, see benmarshall.me/drupal-8-console-commands/.

Flush image styles with Drush

$ drush image-flush

This will create a list of options with all of your defined image styles. For more information run:

$ drush help image-flush

Programmatically flush image styles

<?php
image_style_flush('STYLE_NAME');

Or, if you want to flush all image styles:

<?php
foreach (image_styles() as $style) {
  image_style_flush($style);
}

More on Drupal Image Styles

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

Leave a Reply

Your email address will not be published. Required fields are marked *