jzp74 jzp74 - 1 year ago 102
PHP Question

get image style height in pre process function in Drupal 8

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

element is rendered, more specifically: I need to add the
parameters to the
field. I therefore use the

This hook provides me with a bunch of variables, most notably
are all empty strings for some reason. Fortunately
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):

  1. convert the path to an uri (or is it path)?

  2. Get the file id from the uuid and then somehow get the uri from the styled image (which seems like a detour to get what I want)

I can't get option 1 to work. The path in srcset is like this:
and I think I need to convert that to
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

Answer Source

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'];