Zend Framework Source Code Snippets

Image view helper

Bookmark and Share
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160161
162
163
164
165166
167
168
169
170171
172
173
174
175176
177
178
179
180181
182
183
184
185186
187
188
189
190191
192
193
194
195196
197
198
199
200201
202
203
204
205206
207
208
209
210211
212
213
214
215216
217
218
219
220221
222
223
224
225226
227
228
229
230231
232
233
234
235236
237
238
239
240241
242
243
244
245246
247
248
249
250251
252
253
254
255256
257
258
259
260261
262
263
264
265266
267
268
269
270271
272
273
274
275276
277
278
279
280281
282
283
284
285286
287
288
289
290291
292
293
294
295296
297
298
299
<?php
/**
 * @author     Mohamed Alsharaf
 * @category   Core
 * @package    Core_ViewHelper * @copyright  Copyright (c) 2008-2009 Mohamed Alsharaf.
 * @license    http://framework.zend.com/license/new-bsd  New BSD License
 * @version    0.0.2
 */
class Core_ViewHelper_Html_Image extends Zend_View_Helper_Abstract{
    private $_name = null;
    private $_width = null;
    private $_height = null;
    private $_src = null;    private $_imagePath = null;
    private $_fileName = null;
    private $_imgMime = null;
    private $_validMime = array(
            'image/png',            'image/jpeg',
            'image/jpg',
            'image/gif'
    );
     public function image($name, $imagePath=null,
                          $attribs = array(),
                          $action=null) {
        // set name
        $this->_name = $this->view->escape($name); 
        // set path
        $this->_setImagepath($imagePath);
 
        // set attributes        $this->_setAttributes($attribs);
 
        // add action to image (e.g. generate thumbnail)
        // default action set dimensions
        if(!$this->_setAction($action)) {            $this->_setDimensions();
        }
 
        // render image
        return $this->_render();    }
 
    /**
     * Return image relative path
     *     * @return string
     */
    public function getImagePath() {
        return $this->_imagePath;
    } 
    /**
     * Return image src
     *
     * @return string     */
    public function getSrc() {
        return $this->_src;
    }
     /**
     * Return image width
     *
     * @return string
     */    public function getWidth() {
        return $this->_width;
    }
 
    /**     * Return image height
     *
     * @return string
     */
    public function getHeight() {        return $this->_height;
    }
 
    /**
     * Return image name     *
     * @return string
     */
    public function getImageName() {
        return $this->_fileName;    }
 
    /**
     * Set new image after a specific action applied  on the current image
     *     * @param string $path
     * @return self
     */
    public function setNewImage($path, $width = null, $height = null) {
        // set image new path        $this->_setImagepath($path);
 
        if($width !== null) {
            $this->_width = $width;
        } 
        if($height !== null) {
            $this->_height = $height;
        }
    } 
    /**
     * render image html tag
     *
     * @return string     */
    protected function _render() {
        $xhtml  = '<img src="' . $this->_src . '" ' .
                  $this->_attribs . ' id="' . $this->_name . '"';
        $xhtml .= !empty($this->_width)? ' width="' . $this->_width . '"' : '';        $xhtml .= !empty($this->_height)? ' height="' . $this->_height . '"' : '';
 
        $endTag = " />";
        if (($this->view instanceof Zend_View_Abstract)
            && !$this->view->doctype()->isXhtml()) {            $endTag= ">";
        }
        return $xhtml . $endTag;
   }
    /**
    * Retrieve image sizes and type
    * APPLICATION_PUBLIC constants needed for path to public root
    *
    * @todo add cache beacuse getimagesize() is expensive to use.    * @return boolean
    */
   protected function _setDimensions() {
      // get image size
      $path = PUBLIC_PATH . $this->_imagePath; 
      if(!$imgInfo = @getimagesize($path)) {
             return false;
      }
      // is image mime allowed      if(!in_array($imgInfo['mime'] , $this->_validMime)) {
         return false;
      }
      // set image info
      $this->_imgMime = $imgInfo['mime'];      $this->_height = $imgInfo[1];
      $this->_width  = $imgInfo[0];
      return true;
    }
     /**
     * Set image path
     *
     * @param string $path
     * @return self     */
    protected function _setImagepath($path) {
        $this->_imagePath = $path;
        $this->_fileName = basename($path);
        $this->_src = $this->view->baseUrl($path, true);        return $this;
    }
 
    /**
     * Set image attributes     *
     * @param array $attribs
     * @return self
     */
    protected function _setAttributes($attribs) {        $alt = '';
        $class = '';
        $map = '';
        $class  = '';
        if(isset($attribs['alt'])) {            $alt = 'alt="' . $this->view->escape($attribs['alt']) . '" ';
        }
 
        if(isset($attribs['title'])) {
            $title = 'title="' . $this->view->escape($attribs['title']) . '" ';        } else {
            $title = 'title="' . $this->view->escape($attribs['alt']) . '" ';
        }
 
        if(isset($attribs['map'])) {            $map = 'usemap="#' . $this->view->escape($attribs['map']) . '" ';
        }
 
        if(isset($attribs['class'])) {
            $class = 'class="' . $this->view->escape($attribs['class']) . '" ';        }
        $this->_attribs = $alt . $title . $map . $class;
        return $this;
    }
     /**
     * Set specific action your image. e.g. resize image, crop, etc...
     *
     * @param string $action
     * @return boolean     */
    protected function _setAction($actionCallback) {
        if($actionCallback === null) {
            return false;
        } 
        $options = null;
        $action = $actionCallback;
        if(is_array($actionCallback)) {
            $action = $actionCallback[0];            $options = $actionCallback[1];
        }
        $actionClass = 'Core_ViewHelper_Html_Image_Action_' . ucfirst($action);
        $actionClass = new $actionClass($options);
         // if action class is not valid then return false
        if(!$actionClass instanceof Core_ViewHelper_Html_Image_ActionInterface) {
            return false;
        }
        return $actionClass->build($this);    }
}
 
 
/** * @author     Mohamed Alsharaf
 * @category   Core
 * @package    Core_ViewHelper
 * @copyright  Copyright (c) 2008-2009 Mohamed Alsharaf.
 * @license    http://framework.zend.com/license/new-bsd  New BSD License * @version    0.0.2
 */
interface Core_ViewHelper_Html_Image_ActionInterface
{
    public function build($imageInstance);}
 
 
/**
 * @author     Mohamed Alsharaf * @category   Core
 * @package    Core_ViewHelper
 * @copyright  Copyright (c) 2008-2009 Mohamed Alsharaf.
 * @license    http://framework.zend.com/license/new-bsd  New BSD License
 * @version    0.0.2 */
class Core_ViewHelper_Html_Image_Action_Thumbnail
    implements Core_ViewHelper_Html_Image_ActionInterface
{
    public function build($imageInstance) {        // add your code to generate thumbnail
        return $this->_test($imageInstance);
    }
 
    /**     * Test method to generate the thumbnail
     *
     * @return boolean
     */
    private function _test($imageInstance) {        // dir to where you want to save the thumbnail image
        $relativePath = dirname($imageInstance->getImagePath()) . '/thumbs/';
        $dir = PUBLIC_PATH . '/' . $relativePath;
 
        // create the directory if it does not exist        clearstatcache();
        if(!is_dir($dir)) {
            mkdir($dir, 0777);
        }
        // name of the image based on the size of the thumbnail        // @todo the sizes can be in config file/database. for not its hard coded
        $newFileName = '100x100' . '_'  . $imageInstance->getImageName();
        $thumbPath = $dir . $newFileName;
 
        // if thumbnail exists then set new image and return false        if(file_exists($thumbPath)) {
            $imageInstance->setNewImage($relativePath . $newFileName);
            return false;
        }
         // resize image
        $image = new Moo_Image();
        // open original image to resize it
        // set the thumnail sizes
        // set new image path and quality        $image->open(PUBLIC_PATH . $imageInstance->getImagePath())
              ->resize(100, 100)
              ->save($thumbPath, 75);
 
        // pass new image details to image view helper        $imageInstance->setNewImage($relativePath . $newFileName, $image->getWidth(), $image->getHeight());
        return true;
    }
}
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160161
162
163
164
165166
167
168
169
170171
172
173
174
175176
177
178
179
180181
182
183
184
185186
187
188
189
190191
192
193
194
195196
197
198
199
200201
202
203
204
205206
207
208
209
210211
212
213
214
215216
217
218
219
220221
222
223
224
225226
227
228
229
230231
232
233
234
235236
237
238
239
240241
242
243
244
245246
247
248
249
250251
252
<?php echo $this->image('name', 'img/products/1.jpg', array('alt' => 'image alt'), 'thumbnail'); ?>
 
## Image class
<?php
/** * @copyright  2009, S. Mohammed Alsharaf
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU Public License
 * @author     S. Mohammed Alsharaf (satrun77@hotmail.com)
 * @link       http://www.safitech.com
 * @version    1.0 */
class My_Image
{
        protected $_filename = '';
        protected $_image = '';        protected $_width = '';
        protected $_height = '';
        protected $_mimeType = '';
        protected $_view = null;
        const IMAGETYPE_GIF = 'gif';        const IMAGETYPE_JPEG = 'jpeg';
        const IMAGETYPE_PNG = 'png';
        const IMAGETYPE_JPG ='jpg';
        
        public function setView($view)        {
                $this->_view = $view;
        return $this;   
        }
                protected function _newDimension($forDim,$maxWidth,$maxHeight)
        {
          if ($this->_width > $maxWidth)
          {
                  $ration = $maxWidth/$this->_width;                  $newwidth = round($this->_width*$ration);
                  $newheight = round($this->_height*$ration);
                  if ($newheight > $maxHeight)
                  {
                        $ration = $maxHeight/$newheight;                        $newwidth = round($newwidth*$ration);
                        $newheight = round($newheight*$ration);
 
                        if($forDim == 'w')
                                return $newwidth;                        else
                                return $newheight;
                  }
                  else
                  {                        if($forDim == 'w')
                                return $newwidth;
                        else
                                return $newheight;
                  }          }
          else if ($this->_height > $maxHeight)
          {
                $ration = $maxHeight/$this->_height;
                $newwidth = round($this->_width*$ration);                $newheight = round($this->_height*$ration);
                if ($newwidth > $maxWidth)
                {
                        $ration = $maxWidth/$newwidth;
                        $newwidth = round($newwidth*$ration);                        $newheight = round($newheight*$ration);
                        if($forDim == 'w')
                                return $newwidth;
                        else
                                return $newheight;                }
                else
                {
                        if($forDim == 'w')
                                return $newwidth;                        else
                                return $newheight;
                }
          }
          else          {
                if($forDim == 'w')
                        return $this->_width;
                else
                        return $this->_height;          }
        }
        
        public function open($filename)
        {                $this->_filename = $filename;
                $this->_setInfo();
                switch($this->_mimeType) {
                        case self::IMAGETYPE_GIF:
                                $this->_image = imagecreatefromgif($this->_filename);                        break;
                        case self::IMAGETYPE_JPEG:
                        case self::IMAGETYPE_JPG:
                                $this->_image = imagecreatefromjpeg($this->_filename);
                        break;                        case self::IMAGETYPE_PNG:
                                $this->_image = imagecreatefrompng($this->_filename);
                        break;
                        default:
                        throw new Exception('Image extension is invalid or not supported.');                        break;
                }
        return $this;
        }
         protected function _output($_saveIn=null, $_quality, $_filters=null)
        {
                switch($this->_mimeType) {
                        case self::IMAGETYPE_GIF:
                                return imagegif($this->_image, $_saveIn);                        break;
                        case self::IMAGETYPE_JPEG:
                        case self::IMAGETYPE_JPG:
                                $_quality = is_null($_quality)? 75 : $_quality;
                                return imagejpeg($this->_image, $_saveIn, $_quality);                        break;
                        case self::IMAGETYPE_PNG:
                                $_quality = is_null($_quality)? 0 : $_quality;
                                $_filters = is_null($_filters)? null : $_filters;
                                return imagepng($this->_image, $_saveIn, $_quality, $_filters);                        break;
                        default:
                                throw new Exception('Image cannot be created.');
                        break;
                }        }
        
        public function display($_quality=null, $_filters=null)
        {
                if($this->_view instanceof Zend_View) {                        $this->_view->getResponse()->setHeader('Content-Type', $this->_mimeType);
                } else {
                        header('Content-Type', $this->_mimeType);
                }
                return $this->_output(null,$_quality, $_filters);        }
        
        public function save($_saveIn=null, $_quality=null, $_filters=null)
        {
                return $this->_output($_saveIn,$_quality, $_filters);        }
        
    public function __destruct()
    {
        @imagedestroy($this->_image);    }
        
        protected function _setInfo()
        {
                $imgSize = @getimagesize($this->_filename);                if(!$imgSize) {
                        throw new Exception('Could not extract image size.');
                } elseif($imgSize[0] == 0 || $imgSize[1] == 0) {
                        throw new Exception('Image has dimension of zero.');
                }                $this->_width = $imgSize[0];
                $this->_height = $imgSize[1];
                $this->_mimeType = $imgSize['mime'];
        }
                public function getWidth()
        {
                return $this->_width;
        }
                public function getHeight()
        {
                return $this->_height;
        }
                protected function _refreshDimensions()
        {
                $this->_height = imagesy($this->_image);
                $this->_width = imagesx($this->_image);
        } 
        /**
         * If image is GIF or PNG keep transparent colors
         * 
         * @credit http://github.com/maxim/smart_resize_image/tree/master         * @param $image src of the image
         * @return the modified image
         */
        protected function _handleTransparentColor($image=null)
        {                $image = is_null($image)? $this->_image : $image;
                
            if ( ($this->_mimeType == self::IMAGETYPE_GIF) || ($this->_mimeType == self::IMAGETYPE_PNG) ) {
                $trnprt_indx = imagecolortransparent($this->_image);
                 // If we have a specific transparent color
                if ($trnprt_indx >= 0) {
                        // Get the original image's transparent color's RGB values
                        $trnprt_color    = imagecolorsforindex($this->_image, $trnprt_indx);
                                         // Allocate the same color in the new image resource
                        $trnprt_indx    = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                 
                        // Completely fill the background of the new image with allocated color.
                        imagefill($image, 0, 0, $trnprt_indx);                 
                        // Set the background color for new image to transparent
                        imagecolortransparent($image, $trnprt_indx);
                } elseif ($this->_mimeType == self::IMAGETYPE_PNG) {
                                // Always make a transparent background color for PNGs that don't have one allocated already                        // Turn off transparency blending (temporarily)
                        imagealphablending($image, false);
                 
                        // Create a new transparent color for image
                        $color = imagecolorallocatealpha($image, 0, 0, 0, 127);                 
                        // Completely fill the background of the new image with allocated color.
                        imagefill($image, 0, 0, $color);
                 
                        // Restore transparency blending                        imagesavealpha($image, true);
                }
        return $image;
        }               
        }        
        /**
         * Resize image based on max width and height
         * 
         * @param integer $maxWidth         * @param integer$maxHeight
         * @return resized image
         */
        public function resize($maxWidth, $maxHeight)
        {                if ($this->_width < $maxWidth && $this->_height < $maxHeight) {
                        $this->_handleTransparentColor();
                        return $this;
                }
                                $newWidth = $this->_newDimension('w', $maxWidth, $maxHeight);
                $newHeight = $this->_newDimension('h', $maxWidth, $maxHeight);
                        
                $newImage = imagecreatetruecolor( $newWidth, $newHeight );
        $this->_handleTransparentColor($newImage);        imagecopyresampled($newImage, $this->_image, 0, 0, 0, 0, $newWidth, $newHeight, $this->_width, $this->_height);
    
        $this->_image = $newImage;
        $this->_refreshDimensions();
        return $this;        }
}

Comments

Sir Edward Sir Edward
1 year ago

I can see myself needing something similar to this in my projects. I do have a couple of suggestions that should improve this slightly.

1) I would add a check to $view->doctype->isXhtml() to it so that the closing html / is only displayed on XHTML pages.

I could also see this being used in an image cache kind of way. You could pass the function, in the options, the dimensions of the image you want, and if a version of that size exists then use that, otherwise use GD or ImageMagick to resize an original version of the image to the requested size and save for later use.

This way on a site you could have a large version of the image and also use this to serve out thumbnail sizes as well.

satrun77 satrun77
1 year ago

Thanks for the comments..

these are good suggestions :)

I will implement them when i have a time to upgrade this class.

Alessandro Coscia Alessandro Coscia
1 year ago

getimagesize() is expensive

satrun77 satrun77
1 year ago

thanks for the note but, do you have any suggestion for another alternative?

davedevelopment davedevelopment
1 year ago

It's expensive but necessary, put some caching on top to try and avoid it.

satrun77 satrun77
1 year ago

thanks for your suggestion.

You must login before commenting on a snippet. If you do not have an account, please register.

Snippet description

This simple helper is to generate an image tag

Arguments to pass are:
1. uniqe name for the image tag will be the id attribute.
2. path to the image file.
3. Attributes in the tag.
4. optional string parameter. currently if you enter thumnail it will create a thumnail if its not exists and display it.

any comments and improvement are welcome :)

Snippet details

Created:
satrun77 satrun77
1 year ago
Edited:
satrun77 satrun77
2 months ago
Revision Id:
151
Edit Message:
Upgrade Release
ZF Version
1.8.3
Tags:
view helper view helper image
Comments:
6
Views:
591
Points:
2 (2 votes)

History

r151

Upgrade Release

satrun77 satrun77
2 months ago
diff
r149

Upgrade Release

satrun77 satrun77
3 months ago
diff
r100

Upgrade Release

satrun77 satrun77
1 year ago
diff
r68

Initial Release

satrun77 satrun77
1 year ago
diff
r65

Initial Release

satrun77 satrun77
1 year ago