I use Drupal 8 with the awesome inline responsive images module. I want to make changes to the img field (the fallback image) before the <picture>
element is rendered, more specifically: I need to add the width
and height
parameters to the <img>
field. I therefore use the preprocess_image
hook.
This hook provides me with a bunch of variables, most notably $variables[attributes]
. $variables[width]
, $variables[height]
and $variables[uri]
are all empty strings for some reason. Fortunately $variables[attributes]
contains: $variables[attributes][data-entity-uuid]
and $variables[attributes][srcset]
so at least I have path to the styled image and the uuid to the original image.
I figured there are two ways to get to where I want to go (that is load the styled image and get height and width):
I can't get option 1 to work. The path in srcset is like this: /sites/default/files/styles/image_lightbox/public/inline-images/erf-2.jpg?itok=4_EU9Ttx
and I think I need to convert that to public://styles/image_lightbox/public/inline-images/erf-2.jpg
but got stuck at something like:
$parsed_url = parse_url($variables['attributes']['srcset']);
$path = file_build_uri($parsed_url['path']);
but that still left the /sites/default/files part in there
I can't get option 2 to work. I'm stuck at:
$file_array = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uuid' => $img_uuid]);
$file_id = reset(array_keys($file_array));
$file = File::load($file_id);
$image_uri = ImageStyle::load('image-lightbox')->buildUrl($file->getFileUri());
$image = \Drupal::service('image.factory')->get($image_uri);
This fails at $file = File::load($file_id)
for some reason
After wasting 8 hours of my life in getting this solved I would be very grateful with any help
The answer was much simpler than I thought.
Option 1 turned out to be very easy: Instead of converting /sites/default/files/styles/image_lightbox/public/inline-images/erf-2.jpg?itok=4_EU9Ttx
(from $variables[attributes][srcset]
) to public://styles/image_lightbox/public/inline-images/erf-2.jpg
. I had to convert it to http://hostname/path-to-drupal-install/sites/default/files/styles/image_lightbox/public/inline-images/erf-2.jpg?itok=4_EU9Ttx
which I did like this:
global $base_url;
$image_uri = $base_url.$variables['attributes']['srcset'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.