/ Drupal 8

Create Image Styles and Effects programmatically

In this short article we will learn how to create image styles and how to add image effects programmatically.

Creating image styles

Image styles are stored as configuration entities in Drupal 8. So to create a new image style we simply need to create a ImageStyle instance and save it.

<?php

use Drupal\image\Entity\ImageStyle;

$imageStyle = ImageStyle::create([
  'name' => 'machine_name',
  'label' => 'Label',
])->save();

Add image effects

We will use the ImageStyle::addImageEffect method to do this.

$imageStyle->addImageEffect([
  'id' => 'image_scale_and_crop',
  'weight' => 0,
  'data' => [
    'width' => 500,
    'height' => 500,
]);
$imageStyle->save();

Each image effect is a plugin of the ImageEffect plugin type. You can find the core's image effect plugins under the Drupal\image\Plugin\ImageEffect namespace in the image module.