Get a Image file path (src) on Drupal 8 | Drupal 8

Get a Image file path (src) on Drupal 8

Submitted by editor on Wed, 12/16/2015 - 23:44
Question

How to display an image file (or get the src to render) in Drupal 8 ?

Get the image file src (url)   
    $fid = 1;//The file ID   
    $file = \Drupal\file\Entity\File::load($fid);
    $path = $file->getFileUri();
    OR
    $path = 'public://images/image.jpg';
    $url = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($path);

Get default file path (get original file path)

$url = file_create_url($path);

Get internal path (Server side)

$image_path = drupal_realpath($path);

Get an image style path

Example : Image style : 'medium'
$fid = 1; // The image file ID.
$file = \Drupal\file\Entity\File::load($fid);
$path = $file->getFileUri();
$image_url = \Drupal\image\Entity\ImageStyle::load($style_name)->buildUrl($path);

Comments

Add new comment