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?
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
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'];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With