I’ve rewritten my image helper to extend off of CakePHP’s built in HTML helper, rather than reinvent the wheel. The major benefit of using this helper is that it determines the image dimensions, if not specified, and applies them to the image tag, which is one of Google’s rules to optimize browser rendering.
<?php
/**
* This class builds an image tag. The main purpose of this is to get the image dimensions and
* include the appropriate attributes if not specified. This will improve front end performance.
*
* @author Seth Cardoza <[email protected]>
* @category image
* @package helper
*/
class HtmlImageHelper extends AppHelper
{
var $helpers = array('Html');
/**
* Builds html img tag determining width and height if not specified in the
* attributes parameter.
*
* @param string $src relative path to image including the 'img' directory
* @param array $attributes array of html attributes to apply to the image
*
* @access public
*
* @return no return value, outputs the img tag
*/
public function image($src, $attributes = array()) {
//get width/height via exif data
//build image html
if(file_exists(WWW_ROOT . $src)) {
$image_size = getimagesize(WWW_ROOT . $src);
if(!array_key_exists('width', $attributes) && array_key_exists('height', $attributes)) {
$attributes['width'] = ($image_size[0] * $attributes['height']) / $image_size[1];
} elseif(array_key_exists('width', $attributes) && !array_key_exists('height', $attributes)) {
$attributes['height'] = ($image_size[1] * $attributes['width']) / $image_size[0];
} else {
$attributes['width'] = $image_size[0];
$attributes['height'] = $image_size[1];
}
}
return $this->Html->image($src, $attributes);
}
}