I have articles with custom fields type media. I need to create thumbnails from these images with a fixed widths (1200px, 700px, 450px and 250px
) to display with the picture element and on different views (blog display and article display).
For the article view, I am using a template override with the JImage class to create the thumbnails:
<?php
$fields = $this->item->jcfields;
foreach ($fields as $field):
if ($field->type == 'media'):
$img_path = $field->rawvalue;
$image = new JImage($img_path);
$image->setThumbnailGenerate(true);
$scale_method = JImage::SCALE_INSIDE;
$img_L = $image->createThumbs('1200x12000', $scale_method)[0]->getPath();
$img_M = $image->createThumbs('700x7000', $scale_method)[0]->getPath();
$img_S = $image->createThumbs('450x4500', $scale_method)[0]->getPath();
$img_XS = $image->createThumbs('250x2500', $scale_method)[0]->getPath();
?>
<picture>
<source srcset="<?php echo $img_L ?>" media="(min-width: 2001px)"/>
<source srcset="<?php echo $img_M ?>" media="(min-width: 1201px) and (max-width: 2000px)"/>
<source srcset="<?php echo $img_S ?>" media="(min-width: 701px) and (max-width: 1200px)"/>
<source srcset="<?php echo $img_XS ?>" media="(min-width: 401px) and (max-width: 700px)"/>
<img src="<?php echo $img_M ?>" srcset="<?php echo $img_M . ', ' . $img_L . ' 2x'?>" alt="Responsive image" />
</picture>
<?php endif; ?>
<?php endforeach; ?>
My concern is mostly about performance and method :
- Perfomance: this code implies the thumbnails are recreatred each time the page is loaded (the view can be cached but even though)
- Method: is there a simpler way to create thumbnail creation (for example creating them when the article is saved in the backend)