Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

drupal-8

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?

like image 423
ZyDucksLover Avatar asked Mar 18 '16 15:03

ZyDucksLover


2 Answers

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

like image 183
Magic Stubble Avatar answered Oct 05 '22 12:10

Magic Stubble


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'];
    }
}
like image 31
GiorgosK Avatar answered Oct 05 '22 11:10

GiorgosK