Resize images in rich text html
3
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}}
There are no comments yet
Be the first one to comment