Get Image From Media Entity

Using the media library is a great way to manage images (and other assets really) that may be used multiple times across your site, or even may need to be updated globally.

Programmatically referencing them can be a pain... Here's a simple function that can be used to grab from an image field in a media entity. This will give you the url and the alt properties so you can use them in a template file.

 

// Get the media ID from a field within your node or any other entity
if (!$entity->hasField('field_node_image')) {
	if (!$entity->get('field_node_image')->isEmpty()) {
		$mediaEntityId = $entity->get('field_node_image')->getValue()[0]['target_id'];
		$imageData = getMediaFieldImage($mediaEntityId);
	}
}

function getMediaFieldImage($mediaId) {
	// Use dependency injection as suggested.
    $entityTypeManager = \Drupal::entityTypeManager();
    $loggerFactory = \Drupal::logger('my_module');
    
    // Set a default... 
    $mediaImage = ['url' => '', 'alt' => ''];
    
    // Use a try catch because it fails a bit more gracefully.
    try {
      $media = $entityTypeManager->getStorage('media')->load($mediaId);
      // Get the field instances of type image
      $fieldDefinitions = $media->getFieldDefinitions();
    } catch (\Exception $e) {
      $loggerFactory->error('Error loading media: @error', ['@error' => $e->getMessage()]);
      return $mediaImage;
    }
    $imageField = FALSE;
    
    // This is really assuming that you have a single 'image' field on the media entity.
    // You could also get any other 'type' you want.
    foreach ($fieldDefinitions as $field) {
      if ($field->getType() == 'image') {
        $imageField = $field->getName();
        // If you want to do multiple images... well, change it up.
        break;
      }
    }
    if ($imageField) {
      // Now that we know the field to get data from, we get the field
      // data just like on any other entity.
      $image = $media->get($imageField)->getValue();
      if(!empty($image)) {
        try {
          $fid = $image[0]['target_id'];
          $file = $entityTypeManager->getStorage('file')->load($fid);
          if ($file) {
            $mediaImage['url'] = $file->createFileUrl();
            $mediaImage['alt'] = $image[0]['alt'];
          }
        } catch (\Exception $e) {
          $loggerFactory->error('Error loading file: @error', ['@error' => $e->getMessage()]);
        }
      }
    }
    return $mediaImage;

  }