5

I'm trying to get the width and height of an image in a preprocess file.

I managed to generate the image with a style defined in the media/styles in the admin but I'm not able to render the width and/or height of the generated image (some will say I should just hardcode it in the twig file but I'm actually interested in learning how to get elements I'll need later :))

Here is what I'm using to get the image of a certain content type: Let's assume my field's machine name is "field_image" and my content type is "article";

if (!empty($node->field_image->entity->getFileUri())) {
  $style = ImageStyle::load('medium');
  $image = $node->field_image->entity;
  $variables['image'] = [
    'src' => $style->buildUrl($image->getFileUri())
  ];
}

After that, all I need to do in node--article.html.twig is:

<img src="{{ image.src }}" />

But I also want to get the width and height attributes. How can I do that?

ZyDucksLover
  • 467
  • 1
  • 7
  • 15

2 Answers2

5
if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node->hasField('field_image')) {
        $imageField = $node->field_image;
        $properties = $imageField->getProperties();
    }
}

$properties will hold an array of the attributes your asking for. $imageField is an instance of the Drupal\image\Plugin\Field\FieldType\ImageItem class. You can read the documentation here https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldType%21ImageItem.php/class/ImageItem/8.2.x

Magic Stubble
  • 66
  • 1
  • 3
  • 2
    Must have changed somewhen. It now is inside `$node->field_image->getValue()` or `$node->field_image->first()->getValue()`. – leymannx Apr 22 '18 at 22:15
3

This is the simplest solution I have found

if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node->hasField('field_image')) {
        //get first image on multi value field
        $image = $node->field_image[0]->getValue();

        $width = $image['width'];
        $height = $image['height'];
    }
}
GiorgosK
  • 7,647
  • 2
  • 29
  • 26