Profile picture for user admin
Daniel Sipos
20 Feb 2017

In this article we are going to look at how we can render images using image styles in Drupal 8.

In Drupal 7, rendering images with a particular style (say the default "thumbnail") was by calling the theme_image_style() theme and passing the image uri and image style you want to render (+ some other optional parameters):

$image = theme('image_style', array('style_name' => 'thumbnail', 'path' => 'public://my-image.png'));

You'll see this pattern all over the place in Drupal 7 codebases.

The theme prepares the URL for the image, runs the image through the style processors and returns a themed image (via theme_image()). The function it uses internally for preparing the url of the image is image_style_url() which returns the URL of the location where the image is stored after being prepared. It may not yet exist, but on the first request, it would get generated.

So how do we do it in Drupal 8?

First of all, image styles in Drupal 8 are configuration entities. This means they are created and exported like many other things. Second of all, in Drupal 8 we no longer (should) call theme functions like above directly. What we should do is always return render arrays and expect them to be rendered somewhere down the line. This helps with things like caching etc.

So to render an image with a particular image style, we need to do the following:

$render = [
  '#theme' => 'image_style',
  '#style_name' => 'thumbnail',
  '#uri' => 'public://my-image.png',
  // optional parameters
];

This would render the image tag with the image having been processed by the style.

Finally, if we just want the URL of an image with the image style applied, we need to load the image style config entity and ask it for the URL:

$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl('public://my-image.png');

So that is it. You now have the image URL which will generate the image upon the first request.

Remember though to inject the entity type manager if you are in such a context that you can.

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

Kay 23 Feb 2017 15:30

Render your images with image styles in twig

Thank you for your post. Can you explain, how I use this in twig. In Drupal 7 I could use php in template but in drupal 8 I have to use twig.

kamal 23 Feb 2017 16:24

Drupal 8 / Image by style in twig

Check another solution to render image by style in twig file : https://www.drupal.org/node/2361299#comment-11591109

D8Newbie 21 Mar 2017 17:50

external URL?

What if the image source is an external URL. How would you solve that?

Duff 16 Oct 2017 21:45

Image style

Hi,
Thanks for your article ! I am using the render array technique your describe from a custom block, which I render explicitly from twig using {{ content.my_image_render_array }}. The image actually gets rendered correctly & resized according to my image style, but the "height" & "width" parameter are not emitted in the markup.
I get an & what I expected is a .
Is this the normal behaviour of drupal 8 ?

Thanks

Pleclerc 21 Nov 2017 17:39

Thank you

Thank you, I managed to do what I wanted, I send here a sample of code to inspire other people.

if($entity && $entity->hasField('field_image') && !$entity->get('field_image')->isEmpty()) {
$entity_img_id = $entity->get('field_image')->first()->getValue()['target_id'];
$image = \Drupal::entityTypeManager()->getStorage('file')->load($entity_img_id);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl($image->getFileUri());

  return [
    '#theme' => 'image',
    '#style_name' => 'thumbnail',
    '#uri' => $url,      
  ];
}
Norman 20 Apr 2018 13:53

Create derivate first if doesn't exist

$original_image = $node->field_my_image->entity->getFileUri();
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$destination = $style->buildUri($original_image);
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}
$url = $style->buildUrl($original_image);
Todd Zebert 30 Nov 2020 08:49

In reply to by Norman (not verified)

thanks!

Turns out I wasn't getting a rendered preview of my form image field because there wasn't a derivative "automagically" generated, so this code was key (along with the parts that set the appropriate vars used):

if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}
```
Christophe Galli 18 Mar 2021 18:08

Your examples

The examples that you post have proven most helpful. On many occasions.

Many thanks for you effort and support:-)

Add new comment