In Chapter 4, Theming, we talked about theme hooks and how we use them in render arrays to build output. And we also saw a few examples of theme hooks that come with Drupal core and which can be used for common things (such as links or tables). But images are also something we’ll often end up rendering and there are two ways we can do so (both using theme hooks defined by Drupal core).
First, we can use the image theme hook to simply render an original image. And it’s pretty simple to use it:
return [ '#theme' => 'image', '#uri' => 'public://image.jpg', ];
And this will render the image as is. We can also pass some more options like the alt, title, width or height which will be applied to the image tag as attributes, as well as an array of any other kinds of attributes we may want. Check out template_preprocess_image() for more information on how this works.
Alternatively, the Image module defines the image_style theme hook which we can use to render the image using a given image style:
return [ '#theme' => 'image_style', '#uri' => 'public://image.jpg', '#style_name' => 'large', ];
This theme hook works pretty much the same way except that it has an extra parameter for the ID of the ImageStyle entity we want to use. And the rest of the parameters we find on the image theme hook can also be found here. In fact, image_style delegates to the image theme hook under the hood.
Finally, we may also find ourselves in a situation in which we need to get our hands on the URL of an image using a given image style. We need to work with the ImageStyle configuration entity for this:
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl('public://image.jpg');
Once we load the image style we want, we simply call its buildUrl() method to which we pass the URI of the file for which we want the URL. The first time this URL is accessed, the image variation gets created and stored to disk. Future requests will load it directly from there for improved performance.