Sometimes you need the URL of an image in twig in order to use it as a background image or something. While there are ways to load them in twig, it is more appropriate to do this with a preprocess function. This makes your code more maintainable. 

For Drupal 9 & 10 use:

function template_preprocess_node(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    if ($variables['elements']['node']->field_image->entity) {
      $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('medium');
      $variables['image'] = $style->buildUrl($variables['elements']['node']->field_image->entity->getFileUri());
    }
  }
}


Then, in Twig:

{{ image }} // prints https://mysite.com/sites/default/files/styles/medium/public/image.jpg

You can also do:

function template_preprocess_node(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
      $render = [
        '#theme' => 'image_style',
        '#style_name' => 'medium',
        '#uri' => $variables['elements']['node']->field_image->entity->getFileUri(),
       ];
      $variables['image'] = render($render);
  }
}

This outputs the full rendered image in twig:

{{ image }} // prints <img src="https://mysite.com/sites/default/files/styles/medium/public/image.jpg" ...

Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.