Skip to main content

How to get the url of a styled image

Posted on July 13, 2020


Here is how you get the url of a styled image.

// Load the image file entity.
$file_entity = \Drupal::entityTypeManager()->getStorage('file')->load($file_entity_id);

// Get the uri of the file.
$original_file_uri = $file_entity->getFileUri();

// Get the style you want on the image.
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');

// Build the uri of the styled image.
$styled_file_uri = $style->buildUri($original_file_uri);

// If the styled image file doesn't exist, create it.
if (!file_exists($styled_file_uri)) {
  $style->createDerivative($original_file_uri, $styled_file_uri);
}

// Build the absolute url of the styled image file.
$styled_file_url = $style->buildUrl($styled_file_uri);

If you want the relative url you can use this function: file_url_transform_relative().

In case the image is coming from a field of a content entity, you can set $file_entity to

$file_entity = $article->field_image->entity;

where $article is the content entity and field_image is the image field name.

The title and alt attributes of field_image can be retrieved like so

$image_properties = $article->field_name->first()->getValue();
$title = $image_properties['title'];
$alt = $image_properties['alt'];

 

Note:

If you're puzzled on how the file_exists() works in this case, this can help you find the answer: file_exists() and Drupal file URI -- how does it work?.