Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Is there a simple way to get image width/height in twig?

Started by Muut Archive 10 years ago · 3 replies · 5760 views
10 years ago

I had a situation in my current project where I wanted to add img's to my gallery template differently depending on whether they were portrait or landscape. But there are no built-in actions to determine the width and height of an image file. The width() and height() actions are only to set the width or height.

What I have done for now is to edit the ImageMedium.php file (/system/src/Grav/Common/Page/Medium/ImageMedium.php) by adding these two methods:
---php
public function getWidth()
{
if (!$this->image) {
$this->image();
}
return $this->image->getAdapter()->width();
}

PHP
public function getHeight()
{
    if (!$this->image) {
        $this->image();
    }
    return $this->image->getAdapter()->height();
}
TXT
Now I can call them from twig like this:

{% if page.media[painting.file].getHeight() > page.media[painting.file].getWidth() %}
{% set portrait = true %}
{% else %}
{% set portrait = false %}
{% endif %}

TXT

This is just fine and dandy, except I have to update that file every time grav updates.  Is there a simpler, or at least update-proof way of doing this?  Thanks.
10 years ago

Hmm.. i thought that this was already in ImageMedium.php, but the height() and width() functions in there are actually allowing you to get and set the image height and width attributes, not actually retrieving the physical height and width.

Please create an issue here: https://github.com/getgrav/grav/issues about this and i'll get a couple of functions added to get the physical image sizes.

10 years ago

OK, this was just resolved on github by w00fz. Apparently 'height' and 'width' can be used as properties, in addition to as functions, and will thusly give the actual height and width. Like:

TWIG
{% set imgHeight = page.media[painting.file].height %}

I don't think that's in the documentation, but I could just have missed it.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1368 9 years ago
Archive · by Muut Archive, 9 years ago
2 940 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2960 9 years ago
Archive · by Muut Archive, 9 years ago
3 1125 9 years ago