Skip to main content

Drupal 8: How to render an image style programmaticaly

This is how you can render the Media entity image Style (Entity Reference Field) URL in your php code ( in a custom controller or custom block etc)

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\media\Entity\Media;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

private function getImageStyleUrl(ContentEntityInterface $entity, $image_style = 'thumbnail') {

    $media_ref_id = $entity->get('field_media_gallery')->first()->target_id;
    if (isset($media_ref_id)) {
      $media = Media::load($media_ref_id);
      $fid = $media->field_media_image->target_id;
      $file = File::load($fid);
      //you can find them here: admin/config/media/image-styles
      return ImageStyle::load($image_style)->buildUrl($file->getFileUri());

    return false;



php media