Как я могу получить ширину или высоту изображения поля изображения на Octobercms - PullRequest
0 голосов
/ 08 ноября 2018

Я пытаюсь использовать этот метод для получения размеров изображения:

{% 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 }}">

но безуспешно. Я также попробовал:

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

и

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

но тоже безуспешно.

Есть ли какой-нибудь способ в октябре, чтобы получить размеры изображения с помощью веточки?

1 Ответ

0 голосов
/ 09 ноября 2018

Расширьте twig, чтобы получить исходный размер вашего изображения. Нечто подобное должно работать (не проверено, но вы поймете)

Сначала создайте класс регистрации, см. Здесь ссылку .

<?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];
    }

Если все сделано правильно, вы можете использовать новые фильтры внутри вашего шаблона, как это

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