1

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)
1

You are correct, this way you will be creating thumbnails all the time... One possibility would be to adjust your implementation in such a way, so that it will only create thumbnails on the first load and then store their paths/names in the database. Then you can check against the existence of thumbnails and their consistency with the original file and only recreate them if you have updated the original.

It's also possible to do this during content creation with a content plugin.

https://docs.joomla.org/Plugin/Events/Content#onContentBeforeSave

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.