How can I get the width or height of an image field image on Octobercms

1.8k views Asked by At

I try this method to get image dimensions:

{% set image_width = fields.sec_port_image.width %}
{% set image_height = fields.sec_port_image.height %}

<a href="{{ fields.sec_port_image|media }}" width="{{ image_width }}" height="{{ image_height }}">

but without success. I Also tried:

{% set image_width = fields.sec_port_image.width|media %}

and

{% set image_width = fields.sec_port_image|media.width %}

but also without success.

Is there a way on Octobercms to get image dimensions using twig?

1

There are 1 answers

0
DarkBee On

Extend twig in order to get the original size of your image. Something like this should work (not tested but you'll get the idea)

First create a registration class, see here for a reference.

<?php
    class Registration {
        public function registerMarkupTags()
        {
            return [
                'filters' => [
                    // A global function, i.e str_plural()
                    'image_width' => [$this, 'getImageWidth'],
                    'image_height' => [$this, 'getImageHeight'],
                ],
            ];
        }

        private $images = [];

        public function getImageWidth($url) {
            return $this->getImageSize($url) ? $this->getImageSize($url)['width'] : null;
        }

        public function getImageHeight($url) {
            return $this->getImageSize($url) ? $this->getImageSize($url)['height'] : null;
        }

        private function getImageSize($url) {
            if (!isset($this->images[$url])) {
                $data = @getimagesize($url);
                if ($data) {
                    $this->images[$url] = [
                        'width'     => $data[0],
                        'height'    => $data[1],
                    ];
                }else{
                    $this->images[$url] = false;
                }
            }
        }
        return $this->images[$url];
    }

If done correctly you then could use the new filters inside your template like this

{% set source = fields.sec_port_image|media %}
<a href="{{ source }}" width="{{ source|image_width }}" height="{{ source|image_height }}">