How do I programmatically get the URL of an entity referenced media image field using on a custom_preprocess_html() hook on THEME.theme? Reason: I need to create an Open graph meta tag og:image and pass the URL as content.

On THEME_preprocess_html(), I loaded the node using 

$node = \Drupal::routeMatch()-&gt;getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
      $nid = $node-&gt;id();
      if($node-&gt;hasField('field_image')){
        $image_id = $node-&gt;field_image-&gt;target_id;
        $image = \Drupal::entityTypeManager()-&gt;getStorage('file')-&gt;load($image_id);
      }
}


I have loaded the node and I was able to get the field_image_entity_id as shown. I want to get the URL of the image field of entity referenced field.

The below code gives me NULL. How can I load the media entity and get this value? 

$image = \Drupal::entityTypeManager()-&gt;getStorage('file')-&gt;load($entity_img_id);
ok, here is what worked for me. After digging through stack overflow, found that I was missing the ImageStyle and this resulted in not rendering the url.

I added 

use Drupal\media\Entity\Media;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\MediaInterface;
use Drupal\node\Entity\Node;


and then on preprocess function, I loaded the media using the target_id that I got form the $node->field_image->target_id;

Then, I loaded the ImageStyle using 

$media = Media::load($image_id);
$media_url = ImageStyle::load('TYPE_OF_CROP')-&gt;buildUrl($media-&gt;image-&gt;entity-&gt;getFileUri());
$variables['media_url'] =  $media_url;


Hopefully this helps people.