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

{html_image}

 
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 -> Feature Requests
View previous topic :: View next topic  
Author Message
Serzhik
Smarty Rookie


Joined: 12 Mar 2004
Posts: 18
Location: Kyiv, Ukraine

PostPosted: Tue Apr 27, 2004 10:57 pm    Post subject: {html_image} Reply with quote

I think my modification of smarty_fumction_html_image will be helpful for others.
There is one extra attribute "resize" (Type: boolean, Required: No, Default: false). This modification resize picture to width or height that you want.
Example: {html_image file="1.jpg" width=100 resize=yes}

P.S. Sorry 4 my English.

Code:

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty {html_image} function plugin
 *
 * Type:     function<br>
 * Name:     html_image<br>
 * Date:     Feb 24, 2003<br>
 * Purpose:  format HTML tags for the image<br>
 * Input:<br>
 *         - file = file (and path) of image (required)
 *         - border = border width (optional, default 0)
 *         - height = image height (optional, default actual height)
 *         - image = image width (optional, default actual width)
 *         - resize = resize or not picture to used width or height (optional, default false)
 *         - basedir = base directory for absolute paths, default
 *                     is environment variable DOCUMENT_ROOT
 *
 * Examples: {html_image file="images/masthead.gif"}
 * Output:   <img src="images/masthead.gif" border=0 width=400 height=23>
 * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image}
 *      (Smarty online manual)
 * @author   Monte Ohrt <monte@ispi.net>
 * @author credits to Duda <duda@big.hu> - wrote first image function
 *           in repository, helped with lots of functionality
 * @version  1.0
 * @param array
 * @param Smarty
 * @return string
 * @uses smarty_function_escape_special_chars()
 */
function smarty_function_html_image($params, &$smarty)
{
    require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
   
    $alt = '';
    $file = '';
    $border = 0;
    $height = '';
    $width = '';
    $extra = '';
    $prefix = '';
    $suffix = '';
   $resize = false;
    $basedir = isset($GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'])
        ? $GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'] : '';
    if(strstr($GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'], 'Mac')) {
        $dpi_default = 72;
    } else {
        $dpi_default = 96;
    }

    foreach($params as $_key => $_val) {
        switch($_key) {
            case 'file':
            case 'border':
            case 'height':
            case 'width':
            case 'dpi':
            case 'basedir':
                $$_key = $_val;
                break;

            case 'alt':
                if(!is_array($_val)) {
                    $$_key = smarty_function_escape_special_chars($_val);
                } else {
                    $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;

            case 'link':
            case 'href':
                $prefix = '<a href="' . $_val . '">';
                $suffix = '</a>';
                break;
           case 'resize':
               $$_key = (bool)$_val;
            break;

            default:
                if(!is_array($_val)) {
                    $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
                } else {
                    $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;
        }
    }

    if (empty($file)) {
        $smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
        return;
    }

    if (substr($file,0,1) == '/') {
        $_image_path = $basedir . $file;
    } else {
        $_image_path = $file;
    }

    if(!isset($params['width']) || !isset($params['height'])) {
        if(!$_image_data = @getimagesize($_image_path)) {
            if(!file_exists($_image_path)) {
                $smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
                return;
            } else if(!is_readable($_image_path)) {
                $smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
                return;
            } else {
                $smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
                return;
            }
        }
        $_params = array('resource_type' => 'file', 'resource_name' => $_image_path);
        require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.is_secure.php');
        if(!$smarty->security && !smarty_core_is_secure($_params, $smarty)) {
            $smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE);
            return;
        }

        if(!isset($params['width']) && !$resize) {
            $width = $_image_data[0];
        } elseif (!isset($params['width']) && !$resize) {
         if(isset($params['height'])) $width=(int)($_image_data[0]*$height/$_image_data[1]);
      }
        if(!isset($params['height']) && !$resize) {
            $height = $_image_data[1];
        } elseif (!isset($params['height']) && !$resize) {
         if(isset($params['width'])) $width=(int)($_image_data[1]*$width/$_image_data[0]);
      }

    }

    if(isset($params['dpi'])) {
        $_resize = $dpi_default/$params['dpi'];
        $width = round($width * $_resize);
        $height = round($height * $_resize);
    }

    return $prefix . '<img src="'.$file.'" alt="'.$alt.'" border="'.$border.'" width="'.$width.'" height="'.$height.'"'.$extra.' />' . $suffix;
}

/* vim: set expandtab: */

?>

_________________
http://party.com.ua
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
bsr0bin
Smarty n00b


Joined: 11 Mar 2004
Posts: 4

PostPosted: Fri May 14, 2004 12:44 pm    Post subject: Reply with quote

Does this code actually work ?
I intend to test it, but what puzzles me is these lines :

Code:

if(!isset($params['width']) && !$resize) {
    $width = $_image_data[0];
} elseif (!isset($params['width']) && !$resize) {
    if(isset($params['height'])) $width=(int)($_image_data[0]*$height/$_image_data[1]);
}

Let's translate : "
Code:

If ($params['width'] is not set AND $resize is FALSE) <= cond A
  Then set $width to the image width
ElseIF ($param['width'] is not set AND $resize is FALSE) <= cond B
  Then
      IF ($params['height'] is set)
         Then compute the new image width according to
            * the image actual ratio (w/h)
            * the requested new height
       EndIF
EndIf

... But, isn't it obvious that cond A === cond B ?
A "ElseIf" structure is used when you already have evaluated previous conditions (here, cond A), and you want to do something if the all previous conditions where evaluated to FALSE, and IF a NEW condition is TRUE.
Here, if we hit the "ElseIf", cond A is FALSE, so EITHER $params['width'] is set OR $resize is TRUE, and cond B will also evaluate to FALSE.
What's the point testing again both values ?
if cond A is true, one enters the "IF" statement and don't even test cond B
if cond A is false, cond B will also evaluate to false...
Hence, whatevers the situation, the code inside ElseIf will NEVER be executed.
It's a clear case of "dead code"...

The same goes of the If/ElseIf below about isset($params['height'])...

Is this a typo (I mean, you made an error posting the code here) ?
Back to top
View user's profile Send private message
bsr0bin
Smarty n00b


Joined: 11 Mar 2004
Posts: 4

PostPosted: Fri May 14, 2004 1:59 pm    Post subject: Here is something that would do ... Reply with quote

Ok, here's my version of the resize :

Code:

       /*
          -- intial code --
          if(!isset($params['width'])) {
            $width = $_image_data[0];
        }
          if(!isset($params['height'])) {
            $height = $_image_data[1];
        }
        */
       // if "resize" parameter is not given, behave as usual
       if (!isset($params['resize'])) {
            if(!isset($params['width'])) {
                $width = $_image_data[0];
            }
            if(!isset($params['height'])) {
                $height = $_image_data[1];
            }
        } elseif (($_image_data[1] <= 0) || ($_image_data[1] <= 0)) {
            $smarty->trigger_error("html_image: unable to perform resize on '$_image_path'", E_USER_NOTICE);
            return;
        } else {
            // compute original image ratio: width/height
            $img_ratio = floatval($_image_data[0])/floatval($_image_data[1]) ;
           
            /* 
              ok, this check below is pretty useless, given that
              `($_image_data[1] <= 0) || ($_image_data[1] <= 0)` has already
              been evaluated to FALSE, previously
            */
            $img_ratio = ($img_ratio <= floatval(0)) ? 1 : $img_ratio;
           
            /*
              To perform a `resize` respecting the original ratio of the image,
              one must follow the rule :
                `new_width / new_height = ratio = original_width / original_height`
              So, if given a new_width: new_height = new_width / ratio
              If given a new_height: new_width = ratio * new_height
            */
            if (isset($params['width'])) {
                $height = intval(floatval($width) / $img_ratio);
                $height = ($height <= 0) ? 1 : $height;
            } elseif (isset($params['height'])) {
                $width = intval($img_ratio * floatval($height));
                $width = ($width <= 0) ? 1 : $width;
            }
        }

The "resize" parameter here is more a "resize_with_respect_to_ratio" parameter.
The resize is done accordingly to ONE parameter: width OR height.
So if you want to limit the width of the image to something, and keep a good resize ratio : it's
Code:
{html_image [...] width="200" resize="1"}

If you want to limit the height, it's:
Code:
{html_image [...] height="150" resize="1"}
.

Code:
{html_image [...] width="200" height="150" resize="1"}
or
Code:
{html_image [...] height="150" width="200" resize="1"}
will be understood as
Code:
{html_image [...] width="200" resize="1"}


Keep in mind that my code is nothing but a SIMPLE resize.
If I have time, I may post a more complex resize, that allows to specify boundaries to respect, that is to say "I want a image displayed in a box of (max_width, max_height), and if it has to be resized, please respect the ratio"
Back to top
View user's profile Send private message
Serzhik
Smarty Rookie


Joined: 12 Mar 2004
Posts: 18
Location: Kyiv, Ukraine

PostPosted: Fri May 14, 2004 6:27 pm    Post subject: Reply with quote

Thanks a lot! Now I'm use this code:
Code:
<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty {html_image} function plugin
 *
 * Type:     function<br>
 * Name:     html_image<br>
 * Date:     Feb 24, 2003<br>
 * Purpose:  format HTML tags for the image<br>
 * Input:<br>
 *         - file = file (and path) of image (required)
 *         - border = border width (optional, default 0)
 *         - height = image height (optional, default actual height)
 *         - image = image width (optional, default actual width)
 *         - resize = resize or not picture to used width or height (optional, default false)
 *         - basedir = base directory for absolute paths, default
 *                     is environment variable DOCUMENT_ROOT
 *
 * Examples: {html_image file="images/masthead.gif"}
 * Output:   <img src="images/masthead.gif" border=0 width=400 height=23>
 * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image}
 *      (Smarty online manual)
 * @author   Monte Ohrt <monte@ispi.net>
 * @author credits to Duda <duda@big.hu> - wrote first image function
 *           in repository, helped with lots of functionality
 * @version  1.0
 * @param array
 * @param Smarty
 * @return string
 * @uses smarty_function_escape_special_chars()
 */
function smarty_function_html_image($params, &$smarty)
{
    require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
   
    $alt = '';
    $file = '';
    $border = 0;
    $height = '';
    $width = '';
    $extra = '';
    $prefix = '';
    $suffix = '';
   $resize = false;
    $basedir = isset($GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'])
        ? $GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'] : '';
    if(strstr($GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'], 'Mac')) {
        $dpi_default = 72;
    } else {
        $dpi_default = 96;
    }

    foreach($params as $_key => $_val) {
        switch($_key) {
            case 'file':
            case 'border':
            case 'height':
            case 'width':
            case 'dpi':
            case 'basedir':
                $$_key = $_val;
                break;

            case 'alt':
                if(!is_array($_val)) {
                    $$_key = smarty_function_escape_special_chars($_val);
                } else {
                    $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;

            case 'link':
            case 'href':
                $prefix = '<a href="' . $_val . '">';
                $suffix = '</a>';
                break;
           case 'resize':
               $$_key = (bool)$_val;
            break;

            default:
                if(!is_array($_val)) {
                    $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
                } else {
                    $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;
        }
    }

    if (empty($file)) {
        $smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
        return;
    }

    if (substr($file,0,1) == '/') {
        $_image_path = $basedir . $file;
    } else {
        $_image_path = $file;
    }

    if(!isset($params['width']) || !isset($params['height'])) {
        if(!$_image_data = @getimagesize($_image_path)) {
            if(!file_exists($_image_path)) {
                $smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
                return;
            } else if(!is_readable($_image_path)) {
                $smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
                return;
            } else {
                $smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
                return;
            }
        }
        $_params = array('resource_type' => 'file', 'resource_name' => $_image_path);
        require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.is_secure.php');
        if(!$smarty->security && !smarty_core_is_secure($_params, $smarty)) {
            $smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE);
            return;
        }

      if(!isset($params['width'])) {
         $width = $_image_data[0];
      }
      if(!isset($params['height'])) {
         $height = $_image_data[1];
      }
    }

   // if "resize" parameter is not given, behave as usual
   if ($resize) {
        if(!$_image_data = @getimagesize($_image_path)) {
            if(!file_exists($_image_path)) {
                $smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
                return;
            } else if(!is_readable($_image_path)) {
                $smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
                return;
            } else {
                $smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
                return;
            }
        }

      // compute original image ratio: width/height
      $img_ratio = floatval($_image_data[0])/floatval($_image_data[1]) ;
      $img_ratio = ($img_ratio <= floatval(0)) ? 1 : $img_ratio;
      
      if (isset($params['width']) && isset($params['height'])) {
         $resize_ratio = min(floatval($width)/floatval($_image_data[0]),floatval($height)/floatval($_image_data[1]));
         $resize_ratio = ($resize_ratio <= floatval(0)) ? 1 : $resize_ratio;

         $width=$_image_data[0]*$resize_ratio;
         $height=$_image_data[1]*$resize_ratio;
      } elseif (isset($params['width'])) {
         $height = intval(floatval($width) / $img_ratio);
         $height = ($height <= 0) ? 1 : $height;
      } elseif (isset($params['height'])) {
         $width = intval($img_ratio * floatval($height));
         $width = ($width <= 0) ? 1 : $width;
      }
   }

    if(isset($params['dpi'])) {
        $_resize = $dpi_default/$params['dpi'];
        $width = round($width * $_resize);
        $height = round($height * $_resize);
    }

    return $prefix . '<img src="'.$file.'" alt="'.$alt.'" border="'.$border.'" width="'.$width.'" height="'.$height.'"'.$extra.' />' . $suffix;
}

/* vim: set expandtab: */

?>

This code also allows such variant as:
Code:
html_image [...] width=200 height=100 resize=true

and resize picture to width or height so the picture can't have width more than 200 and height can't be more than 100
_________________
http://party.com.ua
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
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 -> Feature Requests 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