Magento: Custom function to resize image proportionally

In my previous article to resize image in Magento, I had written direct code to resize any image. Here, I will be writing a simple function to resize image proportionally, which can be kept in the helper file of the module (as helper file can be accessed by any template (.phtml) file).

Here is the custom image resize function. This function will resize image proportionally.


/**
 * Resize Image proportionally and return the resized image url 
 *
 * @param string $imageName	        name of the image file
 * @param integer|null $width 		resize width
 * @param integer|null $height 		resize height
 * @param string|null $imagePath 	directory path of the image present inside media directory
 * @return string 				full url path of the image
 */
public function resizeImage($imageName, $width=NULL, $height=NULL, $imagePath=NULL)
{		
	$imagePath = str_replace("/", DS, $imagePath);
	$imagePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $imageName;
	
	if($width == NULL && $height == NULL) {
		$width = 100;
		$height = 100; 
	}
	$resizePath = $width . 'x' . $height;
	$resizePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $resizePath . DS . $imageName;
			
	if (file_exists($imagePathFull) && !file_exists($resizePathFull)) {
		$imageObj = new Varien_Image($imagePathFull);
		$imageObj->constrainOnly(TRUE);
		$imageObj->keepAspectRatio(TRUE);
		$imageObj->resize($width,$height);
		$imageObj->save($resizePathFull);
	}
			
	$imagePath=str_replace(DS, "/", $imagePath);
	return Mage::getBaseUrl("media") . $imagePath . "/" . $resizePath . "/" . $imageName;
}

You can write the following code in template (.phtml) file to display the resized image:


<img src="<?php echo Mage::helper('moduleName')->resizeImage('abc.jpg', 400, 300, 'xyz/image'); ?>" alt="resized image" />

Here,

$imageName is the name of the image (e.g. abc.jpg)

$width is the image resize width (e.g. 400)
$height is the image resize height (e.g. 300)
(400 resembles 400px and 300 resembles 300px)

$imagePath is the path where the image is stored/saved. This directory must be inside ‘media’ directory. Like, if we specify ‘xyz/image‘ as $imagePath then our image path must be ‘media/xyz/image/abc.jpg‘ (the $imageName is abc.jpg)

We have defined the width and height to be 400 and 300 respectively. So, a new folder will be created named ‘400×300’. The new resized image will be saved here.

If width is null and height is 300 then the image will be resized proportionally with fixed height of 300px. And the folder name will be ‘x300’.

If width is 400 and height is null then the image will be resized proportionally with fixed width of 400px. And the folder name will be ‘400x’.

If both width and height are null then the image is resized with height ‘100’ and width ‘100’. And the folder name will be ‘100×100’.

Hope this helps. Thanks.