Drupal 8/9 : change all images src relative path to absolute path

Profile picture for user a.berramou
Azz-eddine BERRAMOU 3 October, 2021

Drupal by default set the src path for all images to relative path something like /sites/default/files/styles/medium/public/2021-09/panda.jpg so if you use your Drupal site as an API and sent the wysiwyg text (Body for instance) contain images then your front site (https://www.front-site.com) will not find your images because your server will look at https://www.front-site.com/sites/default/files/styles/medium/public/2021-09/panda.jpg which it doesn't exits!

So how to change all images src to absolute path?

To change src path of images we need to preprocess image and change the src attribute to do so we will use hook_preprocess_HOOK like the following:

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULENAME_preprocess_image(&$variables) {
  if (isset($variables['uri'])) {
    // Change the image src path to absolute path.
    $variables['attributes']['src'] = file_create_url($variables['uri']);
    // For drupal > 9.3.x
    // @see https://www.drupal.org/node/2940031
    /** @var \Drupal\Core\File\FileUrlGenerator $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $variables['attributes']['src'] = $file_url_generator->generateAbsoluteString($variables['uri']);
  }
}

after clearing the cache you will have
Screenshot image with src absolute

instead of
screenshot image with src relative

Now all your images have absolute path !