How to Programmatically Load Image using Image Style in Drupal 8

May 04, 2018 - 15:37

In Drupal 8 we can load an image using image style in a custom function using the file id of the image. For this first, we have to create an image style by configuration or create a config file for the same
(Example below: image.style.sample_image_style.yml). Note that we can generate the below file after creating an image style and export the same from config synchronization in Drupal 8.


uuid: 4fcc87d8-09cd-40c7-96c7-af51690757ea
langcode: en
status: true
dependencies:
  module:
    - image_effects
name: sample_image_style
label: 'Sample Image Style'
effects:
  439fd8f0-4d9a-4450-a3e7-af51690757ea:
    uuid: 439fd8f0-4d9a-4450-a3e7-af51690757ea
    id: image_effects_set_canvas
    weight: 1
    data:
      canvas_size: relative
      exact:
        width: '160'
        height: '160'
        placement: center-center
        x_offset: 0
        y_offset: 0
      relative:
        left: 0
        right: 0
        top: 0
        bottom: 0
      canvas_color: '#646464FF'

Now we can use this image style to load the image using its file id by passing to a function.

Don't forget to use the controller of the image style along with your function


  use Drupal\image\Entity\ImageStyle;
  ...................................
  ....................................
  public function MyFunction($image_id) {
    global $base_url;
    $style = ImageStyle::load('sample_image_style');
    $images = array();
    if (!empty($image_id)) {
      $photo_file = file_load($image_id);
      $image_url = $style->buildUrl($photo_file->uri->value);
    }
    return $image_url;
  }

The variable $image_url will generate the url of the image from the image style folder. The image style should be loaded using the machine name of the image style. Hope this code snippet is useful. Happy coding!

Get Drupal updates straight to your inbox

To prevent automated spam submissions leave this field empty.

Post your comments / questions