0

我尝试这种方法来获取图像尺寸:

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

但也没有成功。

Octobercms 有没有办法使用树枝获取图像尺寸?

4

1 回答 1

0

扩展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 }}">
于 2018-11-09T07:00:49.377 回答