October CMS resources and help articles

Simple and to the point. Optimized by the community.

Resize images in rich text html

3
by minakari, last modified on July 23rd, 2024

Images that are inserted by users into rich text fields are not resized. This twig filter as part of a custom plugin does that and can be inserted before |content or |raw:

<?php namespace Minakari\Customisations;
use \System\Classes\ResizeImages;

class Plugin extends PluginBase
{
    public function boot()
    {
    }

    public function registerMarkupTags(): array
    {
        $filters = [
            'rich_resize' => [$this, 'richResize']
        ];
        $functions = [];

        return [
            'filters' => $filters,
            'functions' => $functions,
        ];
    }

    public function richResize($html)
    {
        // Use DOMDocument to parse the HTML and find all image tags
        $dom = new \DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));

        $images = $dom->getElementsByTagName('img');

        foreach ($images as $image) {
            $src = $image->getAttribute('src');

            // Resize the image using the ResizeImages::resize() interface
            $resizedSrc = ResizeImages::resize($src, 1328, null, ['mode' => 'auto', 'quality' => '40', 'compress' => true]);

            // Replace the original src with the resized src
            $image->setAttribute('src', $resizedSrc);
        }

        // Return the modified HTML
        return $dom->saveHTML();
    }
}

It can be used as follows: {{your_field|rich_resize|content}} or `{{your_field|rich_resize|raw}}

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?