Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

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

By editor , 16 December, 2015
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();
    $url = $file->createFileUrl();
    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);
OR
$url = $file->createFileUrl();

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

Tags

  • Drupal 8
  • Code
  • Images
  • Drupal 9
  • Add new comment

Comments2

Plain text

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

Granville (not verified)

10 years 7 months ago

small issue in last line

I think it should be

$url = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($path);

  • Reply

editor

10 years 6 months ago

In reply to small issue in last line by Granville (not verified)

Yes, Thank you.

Yes, Thank you.

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer