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

Get a Image file path (src) on Drupal 8/9

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);

Get relative path

$image_style = \Drupal\image\Entity\ImageStyle::load('large');
$image_uri = $imageFile->getFileUri();
$url = $image_style ? $image_style->buildUrl($image_uri) : file_create_url($image_uri);
$url = file_url_transform_relative($url);

Comments

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.