Smarty Forum Index Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon.

A smarty plugin to create thumbs with Imagemagick

 
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Plugins
View previous topic :: View next topic  
Author Message
jimmy230
Smarty Rookie


Joined: 14 Mar 2009
Posts: 9

PostPosted: Fri Mar 01, 2019 1:54 am    Post subject: A smarty plugin to create thumbs with Imagemagick Reply with quote

You can read how to create this plugin in my Blog

https://wkwebbuilder.com/index.php?action=ViewBlogArticle&id=8

Code:
<?php
function smarty_function_thumbmagick($params, $template)
{
    if (empty($params['source'])) {
        trigger_error("thumbmagick: missing 'source' parameter", E_USER_NOTICE);
        /* we neeed some kind of error handling so this parameter can not be empty right */
        return;
    } else {
        $source = $params['source'];
        /* if everything went ok, then here we have our path to the image */
    }
    if (!isset($params['w'])) { /* check if we recive w if not then just declare null */
        $w = null;
    } else {
        $w = $params['w'];
    }
    if (!isset($params['h'])) { /* check if we recive h if not then just declare null */
        $h = null;
    } else {
        $h = $params['h'];
    }
    if (!isset($params['q'])) {  /* check if we recive q if not then just assign 90 as default quality */
        $q = 90;
    } else {
        $q = $params['q'];
    }
    $images_folder = "thumbs/";
    /* folder where we will save our new resized images */
    /* lets create a folder to save our thumbs you can skip this section if you already created a folder to save the thumbs */
    if (!(is_dir($images_folder))) {
        mkdir($images_folder, 0777, true) or die("Unable to make directory: " . $images_folder);
    }
    $convert   = '/usr/bin/convert';
    /* Where is Imagemagick: this could be something like /usr/bin/convert or /opt/local/share/bin/convert */
    /* Lets get the image file extension here we are going to need it later to name our new file */
    $fileParts = explode('.', $source);
    $count     = count($fileParts) - 1;
    $ext       = $fileParts[$count];
    $filename  = md5_file($source);
    /* change the file name to MD5 */
    /*
    -This is the first change, now we are creating some options to name our file depending on what params we recive,
    -we will use this as a reference to check if the thumb already exists
    but also create some other option to resize our image, like if we only recive w then h will be auto or viceversa.
    */
    if (!empty($w) and !empty($h)) {
        $SavePath = $images_folder . $filename . '_w' . $w . '_h' . $h . '.' . $ext;
        /* if we recive w and h this will handle the name */
    } elseif (!empty($w)) {
        $SavePath = $images_folder . $filename . '_w' . $w . '.' . $ext;
        /* if we recive only w this will handle the name */
    } elseif (!empty($h)) {
        $SavePath = $images_folder . $filename . '_h' . $h . '.' . $ext;
        /* if we recive only h this will handle the name */
    } else {
        return false;
    }
    $CreateThumb = true;
    /* lets define this var as true first */
    /* lets check if the thumb was created before so we can just return the thumb */
    if (file_exists($SavePath) == true) {
        $CreateThumb       = false;
        $origFileTime = date("YmdHis", filemtime($source));
        $newFileTime  = date("YmdHis", filemtime($SavePath));
        if ($newFileTime < $origFileTime) {
            $CreateThumb = true;
        }
    }
    if ($CreateThumb == true) { /* if the thumb doesn't exist lets just created ok */
        if (!empty($w) and !empty($h)) {
            exec($convert . " " . $source . " -resize " . $w . "x" . $h . "^ -gravity center -crop " . $w . "x" . $h . "+0+0 +repage -quality " . $q . " " . $SavePath);
        } elseif (!empty($w)) {
            exec($convert . " " . $source . " -thumbnail " . $w . " -quality " . $q . " " . $SavePath);
        } elseif (!empty($h)) {
            exec($convert . " " . $source . " -thumbnail x" . $h . " -quality " . $q . " " . $SavePath);
        }
    }
    /*
    here is another important part to make changes, so we are returning the new file, so I just want to show the image lets make a var to return the image.
    */
    $result = '<img src="' . $SavePath . '"/>';
    return $result;
    /* here we return the new image so the result will look something like this "<img src="thumbs/imagewithnewname.jpg"> */
}
?>
Back to top
View user's profile Send private message
AnrDaemon
Administrator


Joined: 03 Dec 2012
Posts: 1785

PostPosted: Fri Mar 01, 2019 6:49 pm    Post subject: Reply with quote

I fixed your message formatting, please recheck.
Back to top
View user's profile Send private message
jimmy230
Smarty Rookie


Joined: 14 Mar 2009
Posts: 9

PostPosted: Sat Mar 02, 2019 12:08 am    Post subject: yes thank you Reply with quote

I was in a hurry.
Back to top
View user's profile Send private message
jimmy230
Smarty Rookie


Joined: 14 Mar 2009
Posts: 9

PostPosted: Sat Mar 02, 2019 4:58 am    Post subject: The final version. Reply with quote

Code:

<?php
/**
 * Smarty plugin
 *
 * @package    Smarty
 * @subpackage PluginsFunction
 */
/**
 * Smarty {thumbmagick} function plugin
 * Type:     function
 * Name:     thumbmagick
 * Date:     Mar 02, 2019
 * Purpose:  Create image thumbs
 * Examples: {thumbmagick source="/images/demo1.jpg" w=400}
 * Output:   <img src="/images/demo1.jpg" width=400>
 * Params:
 *
 * - source        - (required) - file (and path) of image
 * - h       - (optional) - image height (default actual height)
 * - w       - (optional) - image width (default actual width)
 * - c       - (optional) - crop  ex. crop=true
 * - q       - (optional) - image quality  ex. q=90  (0 to 100) 
 * - s       - (optional) - scale  ex. s=true
 * - m       - (optional) - Max only  ex. m=true
 * - html    - (optional) - html to include in the image tag html=" itemprop='image' class='' alt='' title='' "
 * - link    - (optional) - link=true, you need to specify the linkurl (true or false)
 * - linkurl  - (optional) - Add a link to the image (default to image source)
 * - linkclass  - (optional) - linkclass="someclass" Add a a class to the image link <a>. if you need to add more styles use linkhtml
 * - linkhtml  - (optional) - linkhtml=" class='' title=''  " adds html to the link <a>
 * - window  - (optional) - ex. window=true, if linkurl Opens the link in a new window  target="_blank" (default target="_self")
 * - friendly_url  - (optional) - friendly_url=true (true or false)   Add a friendly link to the image (default false)
 * - friendly_url_link  - (optional) - Add a friendly link to the image (friendly url: ex domain.com/myimage)
 * - rtn  - (optional) - rtn=true returns only the image path without <img src="">
 * - reflect  - (optional) - reflect=true adds reflection effect to the image need 3 more values. (default false) must have w and h
 * - reflect_topc  - rgba value ex. reflect_topc="232,232,232,0.1"
 * - reflect_bottomc  - rgba value ex. reflect_topc="0,0,0,1"
 * - reflect_height  - reflect_height=30 (values in px)
 * - cache_time - Cache lifetime before the thumb will be recreated ex. cache_time=1   (1=1day , default to 1 day)
 * - cache  - (optional) specify a cache folder for the thumbs (default cache/)
 * - remote  - (optional) specify a download folder for remote images  (default remote/)
 * - compress  - (optional) compress=true if image ext png you can enable compression (default false)
 *
 * @link    https://www.wkwebbuilder.com/index.php?action=ViewBlogArticle&id=8 {thumbmagick}
 * @author  Jaime Gonzalez <wkwebbuilder dot com>
 * @version 1.0
 *
 * @param array                    $params   parameters
 * @param Smarty_Internal_Template $template template object
 *
 * @throws SmartyException
 * @return string
 */
function smarty_function_thumbmagick($params, $template)
{
    if (empty($params['source'])) {
        trigger_error("thumbmagick: missing 'source' parameter", E_USER_NOTICE);
        return;
    } else {
        $source = $params['source'];
    }
    if (!isset($params['w']))
        $params['w'] = null;
    if (!isset($params['h']))
        $params['h'] = null;
    if (!isset($params['q']))
        $params['q'] = 90;
    /* quality will default to 90 if we don't specify it */
    if (!isset($params['c']))
        $params['c'] = false;
    /* crop the image */
    if (!isset($params['s']))
        $params['s'] = false;
    /* scale the image */
    if (!isset($params['m']))
        $params['m'] = null;
    if (!isset($params['html']))
        $params['html'] = null;
    if (!isset($params['linkurl']))
        $params['linkurl'] = null;
    if (!isset($params['friendly_url']))
        $params['friendly_url'] = null;
    if (!isset($params['friendly_url_link']))
        $params['friendly_url_link'] = null;
    if (!isset($params['rtn']))
        $params['rtn'] = null;
    if (!isset($params['link']))
        $params['link'] = true;
    /* if we don't specify a link by default will be the image link */
    if (!isset($params['linkclass']))
        $params['linkclass'] = false;
    if (!isset($params['linkhtml']))
        $params['linkhtml'] = false;
    if (!isset($params['window']))
        $params['window'] = false;
    if (!isset($params['reflect']))
        $params['reflect'] = null;
    if (!isset($params['cache_time']))
        $params['cache_time'] = 1;
    /* default to 1 day */
    if (!isset($params['cache']))
        $params['cache'] = 'cache/';
    if (!isset($params['remote']))
        $params['remote'] = 'remote/';
    /* lets create some default values just in case */
    if (empty($params['w']) and empty($params['h'])) {
        /* if we don't specify w and h then the thumb will be resize to 480px width change this value as youu need */
        $params['w'] = 480;
    }
    $w              = $params['w'];
    $h              = $params['h'];
    $q              = $params['q'];
    $cache_lifetime = $params['cache_time'];
    $cacheFolder    = $params['cache'];
    $convert        = '/usr/bin/convert'; # this could be something like /usr/bin/convert or /opt/local/share/bin/convert
    if (isset($params['reflect'])) {
        if (empty($params['reflect_topc']))
            $params['reflect_topc'] = "232,232,232,0.1";
        /* rgba values start from top */
        if (empty($params['reflect_bottomc']))
            $params['reflect_bottomc'] = "0,0,0,1";
        /* rgba values start from bottom */
        if (empty($params['reflect_height']))
            $params['reflect_height'] = 100;
        /* default to 100 px */
    }
    $check_dir_cache = $params['cache'];
    if (!(is_dir($check_dir_cache))) {
        mkdir($check_dir_cache, 0777, true) or die("Unable to make directory: " . $params['cache']);
    }
    $purl = parse_url($params['source']);
    /* let's parse the image path to see if it has http or https meaning is a remote image */
    if (isset($purl['scheme']) && ($purl['scheme'] == 'http' || $purl['scheme'] == 'https')):
        $finfo = pathinfo($source);
        list($filename) = explode('?', $finfo['basename']);
        $local_filepath = $params['remote'] . $filename;
        $download_image = true;
        if (file_exists($local_filepath)):
            if (filemtime($local_filepath) < strtotime('+' . $cache_lifetime . ' days')): /* you can change this value to minutes, hours, weeks, months, */
                $download_image = false;
            endif;
        endif;
        if ($download_image == true):
            $img = file_get_contents($source);
            file_put_contents($local_filepath, $img);
        endif;
        $source = $local_filepath;
    endif;
    if (file_exists($source) == false) {
        $source = $_SERVER['DOCUMENT_ROOT'] . $source;
        if (file_exists($source) == false) {
            return 'image not found';
        }
    }
    $fileParts = explode('.', $source);
    $count     = count($fileParts) - 1;
    $ext       = $fileParts[$count];
    if (isset($params['reflect']) && $params['reflect'] == true) {
        $ext = "png";
    }
    $imgPath  = str_replace('.' . $ext, '', $source);
    $filename = md5_file($source);
    if (!empty($w) and !empty($h)) {
        $SavePath = $cacheFolder . $filename . '_w' . $w . '_h' . $h . (isset($params['reflect']) && $params['reflect'] == true ? "_rf" : "") . (isset($params['c']) && $params['c'] == true ? "_cp" : "") . (isset($params['s']) && $params['s'] == true ? "_sc" : "") . '.' . $ext;
    } elseif (!empty($w)) {
        $SavePath = $cacheFolder . $filename . '_w' . $w . (isset($params['reflect']) && $params['reflect'] == true ? "_rf" : "") . '.' . $ext;
    } elseif (!empty($h)) {
        $SavePath = $cacheFolder . $filename . '_h' . $h . (isset($params['reflect']) && $params['reflect'] == true ? "_rf" : "") . '.' . $ext;
    } else {
        return false;
    }
    $create = true;
    if (file_exists($SavePath) == true) {
        $create       = false;
        $origFileTime = date("YmdHis", filemtime($source));
        $newFileTime  = date("YmdHis", filemtime($SavePath));
        if ($newFileTime < $origFileTime) {
            $create = true;
        }
    }
    if ($create == true) {
        if (isset($params['reflect']) && $params['reflect'] == true) {
            $tmedia    = "tmpimage_" . rand() . ".jpg";
            $TempImage = $params['cache'] . "/" . $tmedia;
            if (!empty($w) and !empty($h)) {
                exec($convert . " " . $source . "  -resize " . $w . "x" . $h . "^ -gravity center -crop " . $w . "x" . $h . "+0+0  +repage   -quality " . $params['q'] . " " . $TempImage);
            } elseif (!empty($w)) {
                exec($convert . " " . $source . " -resize " . $w . "x  +0+0  +repage ^ -gravity center -quality " . $params['q'] . " " . $TempImage);
            } elseif (!empty($h)) {
                exec($convert . " " . $source . " -resize x" . $h . "+0+0  +repage ^ -gravity center -quality " . $params['q'] . " " . $TempImage);
            }
            list($tw, $th, $type, $attr) = getimagesize($TempImage);
            $reflect_topc    = $params['reflect_topc'];
            $reflect_bottomc = $params['reflect_bottomc'];
            $reflect_height  = $params['reflect_height'];
            if (empty($params['reflect_height'])) {
                $params['reflect_height'] = $th / 3.5;
            }
            $ImgHeight = $params['reflect_height'] + $th;
            exec($convert . " " . $TempImage . " -alpha on \( +clone -flip -size " . $tw . "x" . $reflect_height . " 'gradient:rgba(" . $reflect_topc . ")-rgba(" . $reflect_bottomc . ")'  -alpha off -compose CopyOpacity -composite \) -channel rgba   -append  -gravity North  -crop " . $tw . "x" . $ImgHeight . "+0-5\!\   -background none -compose Over -flatten " . $SavePath);
            unlink($TempImage);
        } else {
            if (!empty($w) and !empty($h)) {
                list($width, $height) = getimagesize($source);
                $resize = $w;
                if ($width > $height) {
                    $resize = $w;
                    if (isset($params['c']) && $params['c'] == true) {
                        $resize = "x" . $h;
                    }
                } else {
                    $resize = "x" . $h;
                    if (isset($params['c']) && $params['c'] == true) {
                        $resize = $w;
                    }
                }
                if (isset($params['s']) && $params['s'] == true) {
                    exec($convert . " " . $source . "  -resize " . $resize . " -quality " . $params['q'] . " " . $SavePath);
                } else {
                    exec($convert . " " . $source . "  -resize " . $w . "x" . $h . "^ -gravity center -crop " . $w . "x" . $h . "+0+0  +repage   -quality " . $params['q'] . " " . $SavePath);
                }
            } elseif (!empty($w)) {
                exec($convert . " " . $source . " -thumbnail " . $w . "" . (isset($params['m']) && $params['m'] == true ? "\>" : "") . " -quality " . $params['q'] . " " . $SavePath);
            } elseif (!empty($h)) {
                exec($convert . " " . $source . " -thumbnail x" . $h . "" . (isset($params['m']) && $params['m'] == true ? "\>" : "") . " -quality " . $params['q'] . " " . $SavePath);
            }
        }
      
    /* To use pngquant you must install it first in your server https://pngquant.org/ */
    if ($ext == "png" and $params['compress'] == true) {
        /* If image extension is png and compress = true lets compress the image */
      $pngquant        = '/usr/bin/pngquant';
        $max_quality = 80;
        $min_quality = 65;
        $CompressThumb = shell_exec($pngquant."  --quality=".$min_quality."-".$max_quality." --skip-if-larger --force --ext .png ".$SavePath);
    }      
}
    # return cache file path   
    $_DST['string'] = ' rel="' . $source . '"  width="' . $w . '" height="' . $h . '"';
    if (empty($params['html']))
        $_RETURN['img'] = '<img itemprop="image" src="' . $SavePath . '" ' . $params['html'] . ' ' . $_DST['string'] . ' alt="" title="" />';
    else
        $_RETURN['img'] = '<img itemprop="image" src="' . $SavePath . '" ' . $params['html'] . ' ' . $_DST['string'] . ' />';
    list($nwidth, $nheight, $type, $attr) = getimagesize($SavePath);
    if ($params['link'] == true) {
        if (isset($params['friendly_url_link']) && !empty($params['friendly_url_link'])) {
            if ($params['friendly_url'] == true) {
                $link = $params['friendly_url_link'];
            }
        } elseif (isset($params['linkurl']) && !empty($params['linkurl'])) {
            $link = $params['linkurl'];
        } else {
            $link = $source;
        }
        if (isset($params['linkclass']) && !empty($params['linkclass'])) {
            $lnclass = "class='" . $params['linkclass'] . "'";
        } else {
            $lnclass = "";
        }
        if (isset($params['linkhtml']) && !empty($params['linkhtml'])) {
            $linkhtml = $params['linkhtml'];
        } else {
            $linkhtml = "";
        }
        if ($params['window'] == true)
            $result = '<a  ' . $linkhtml . '  ' . $lnclass . ' href="' . $link . '" target="_blank">' . $_RETURN['img'] . '</a>';
        elseif ($params['rtn'] == true)
            $result = $SavePath;
        elseif ($params['rtnstyle'] == true)
            $result = 'style="width:100%;height:' . $nheight . 'px"';
        else
            $result = '<a ' . $linkhtml . ' ' . $lnclass . ' href="' . $link . '">' . $_RETURN['img'] . '</a>';
    } else {
        $result = $_RETURN['img'];
    }
    return $result;
}
?>


Last edited by jimmy230 on Sat Mar 02, 2019 11:33 am; edited 1 time in total
Back to top
View user's profile Send private message
AnrDaemon
Administrator


Joined: 03 Dec 2012
Posts: 1785

PostPosted: Sat Mar 02, 2019 11:11 am    Post subject: Reply with quote

Again, please use [code] tag to format your code.
Back to top
View user's profile Send private message
jimmy230
Smarty Rookie


Joined: 14 Mar 2009
Posts: 9

PostPosted: Sat Mar 02, 2019 11:34 am    Post subject: I got it. thank you. Reply with quote

AnrDaemon wrote:
Again, please use [code] tag to format your code.
Back to top
View user's profile Send private message
Display posts from previous:   
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Plugins All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP