Drupal 8 - Get the image width / height / alt / etc.. in a twig or preprocess file

ZyDucksLover picture ZyDucksLover · Mar 18, 2016 · Viewed 8.6k times · Source

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?

Answer

Magic Stubble picture Magic Stubble · Jul 26, 2016
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