How to get image style URL for a specific image file

By nnevill, 3 August, 2023

Here is a simple but useful function for getting image style path:

/**
 * @param $fid
 *   Image file ID.
 * @param $image_style
 *   Image style machine name.
 *
 * @return string|bool
 *   Image style path string or FALSE if file or image broken or missing.
 */
function getImageStylePath($fid, $image_style) {
  // Getting entity type manager to load file and image style later.
  $entity_type_manager = \Drupal::service('entity_type.manager');
  // Loading file.
  $file = $entity_type_manager->getStorage('file')->load($fid);

  if (!$file) {
    return FALSE;
  }

  // Getting origin image file URI.
  $image_uri = $file->getFileUri();
  // Loading image style.
  $style = $entity_type_manager->getStorage('image_style')->load($image_style);

  if (!$style) {
    return FALSE;
  }

  // Getting image style URL.
  return $style->buildUrl($image_uri);
}

 

Short Description
Helper method to get image style URL based on image file id and image style machine name.