Simple Image Resize On The Fly

I use this controller on my webapp to load and resize images (if needed). The controller is based on this code shiftingpixel.com/2008/03/03/smart-image-resizer/

Example of usage: <img src="mysite.com/index.php?r=image/get&image=/images/cover.jpg&width=2000&height=600" />

[b][color="#FF0000"]Two warnings:

  • The image folder must be writable by the web server

  • It does not work when the query is in path format[/color][/b]

[color="#0000FF"]Download[/color]

4617

ImageController.php

Hi

Interesting Controller. I made some modifications to set the cache directory to the assets directory and I modified the ‘crop’ parameter to ‘false’ by default.

I also extend CHtml in my project and I modified ‘image’ like this:




class YHtml5 {


	/**

	 * Generates an image tag.

	 * @param string $src the image URL

	 * @param string $alt the alternative text display

	 * @param array $htmlOptions additional HTML attributes (see {@link tag}).

	 *                           Add height and/or width to enable automatic image resizing.

	 * @return string the generated image tag

	 */

	public static function image($src,$alt='',$htmlOptions=array())

	{

		if(!strncmp($src,'/',1)) {

		    $params=array('image'=>$src);

		    if(isset($htmlOptions['height'])) {

		        $params['height']=$htmlOptions['height'];

		    }

		    if(isset($htmlOptions['width'])) {

		        $params['width']=$htmlOptions['width'];

		    }

		    if(count($params)!=1) {

		        $src=Yii::app()->createUrl('image/get',$params);

		    }

		}

	    $htmlOptions['src']=$src;

		$htmlOptions['alt']=$alt;

		return self::tag('img',$htmlOptions);

	}

[size=2]}[/size]



Use is then like this :


echo YHtml5::image('/images/app-logo.jpg',"logo",array('width'=>50)

You may want to create a variant on the ‘image’ function because specifying both width and height may lead to disproportional scaling.