Somewhere there already exists a plugin that creates responsive thumbs… Can’t remember who created this and I modified it for my purposes.
$oldFunction = kirbytext::$tags['image'];
$attr = ['crop'];
kirbytext::$tags['image'] = [
'attr' => array_merge($oldFunction['attr'], $attr),
'html' => function ($tag) use ($oldFunction) {
$image = $tag->file($tag->attr('image'));
if (!$image) {
return $result = call($oldFunction['html'], $tag);
}
$widths = c::get(
'responsiveimage.widths',
[
2400,
2200,
2000,
1800,
1400,
1200,
1000,
800,
600,
400,
320,
]
);
$srcset = [];
foreach ($widths as $width) {
if ($image->width() < $width) {
continue;
}
$imageResized = $image->resize($width);
if($tag->attr('crop')) {
$imageResized = $image->focusCrop($width, $width/$tag->attr('crop'));
}
$srcset[] = $imageResized->url() . ' ' . $imageResized->width() . 'w';
}
$result = call($oldFunction['html'], $tag);
$result = str_replace('<img', '<img srcset="' . implode(', ', $srcset) . '"', $result->toString());
return $result;
}
];
Edit: Found the source: https://github.com/Pascalmh/kirby-responsiveimage/blob/master/kirby-responsiveimage.php
Would make sense to mix and match the two approaches. Because while this creates the srcset attribute, it doesn’t replace the original image.