4

I'm using JImage to create thumbnails for some images in a component, with a code similar to this:

// Set the desired sizes for our thumbnails.
$sizes = array('300x300');

// Create our object
$image = new JImage(JPATH_SITE . '/path/to/image.png');

// Create the thumbnails
$image->createThumbs($sizes, JImage::SCALE_INSIDE);

Because all my images have landscape format, this creates thumbnails with a width of 300px and varying height, inside the thumbs subfolder, and the name is a combination of the original name and the resulting size, e.g. /path/to/thumbs/image_300x128.png.

But how can I get the thumbnail image name in order to display it? From the component parameters I get the name of the original image, but the thumbnail name will depend on the aspect ratio of the original image, and I can only be sure of the first part (image_300......png).

I guess I can list all images in the thumbs folder, and check for file names containing the original name, but I'm hoping there are simpler ways to do this.

Any ideas?

2 Answers 2

6

Store the result of createThumbs, it will return an array of JImages on which you can retrieve whatever you need.

$thumbs = $image->createThumbs($sizes, JImage::SCALE_INSIDE);
foreach($thumbs as $thumb){
    echo $thumb->getPath();
}

Another solution could be renaming the thumbnails to easily retrieve them later with some name convention:

$thumbs = $image->generateThumbs($sizes, JImage::SCALE_INSIDE);
$counter = 0;
foreach($thumbs as $thumb){
    $thumb->toFile(JPATH_SITE.'/path/to/thumbs/imagename'.$counter.'.png');
    $counter++;
}
2

I ended up generating the thumbnails right inside the <img> tag, using the answer from @NicolaCiciliot ($thumb->getPath();).

A bit simplified, this is what it looks like:

<?php 
$image = new JImage('/path/to/image.png'; ?>        
<img src="<?php echo $image->createThumbs('300x300', JImage::SCALE_INSIDE)[0]->getPath(); ?>" />

If no thumbnail exists, it's generated, and getPath() returns the full path whether the thumbnail already exists or has to be generated.

I'm not sure if this will give any noticable performance hit, but it seems to work fine.

1
  • 1
    This will generate new thumbnail everytime the page is loaded. Any idea how to check whether the thumbnail is already exist?
    – webchun
    Commented Jul 19, 2016 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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