Using the Image Helper to create Thumbnails

Submitted by remo - 7 years ago

Generating a thumbnail from a picture is a common task, whether it is about creating a thumbnail or just a safety measure to shrink picture directly taken from the latest camera. Here's how it works.

// get the file with the ID 123
$fileObject = File::getByID(123);

// alternatively, you can get a file by the attribute handle "pic" from the page
// with the ID 1
$page = Page::getByID(1);
$fileObject = $page->getAttribute('pic');

// check if we have a proper image object
if ($fileObject instanceof File) {
    // Load image helper
    $ih = Loader::helper('image');
    // the maximum width and height of the thumbnail
    $maxWidth = 400;
    $maxHeight = 300;
    // specify true if you want to crop the picture to the exact dimensions
    // defined by $maxWidth and $maxHeight
    $crop = false;
    $thumbnail = $ih->getThumbnail($fileObject, $maxWidth, $maxHeight, $crop);
    // check if we have a thumbnail object
    if (is_object($thumbnail)) {
        echo '<img src="' . $thumbnail->src . '" width="' . $thumbnail->width . '" height="' . $thumbnail->height . '" alt=""/>';        
Stats Categories Tags
comments powered by Disqus