How to render your images with image styles in Drupal 8
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.